1

I'm migrating an web api from .Net to .NetCore.

We had a custom ExceptionFilterAttribute to handle errors in a centralized way. Something like this:

public class HandleCustomErrorAttribute : ExceptionFilterAttribute
{
   public override void OnException(HttpActionExecutedContext filterContext)
   {
     // Error handling routine
   }
}

With some search, I managed to create something similar on .Net Core

public static class ExceptionMiddlewareExtensions
    {
        public static void ConfigureExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";

                    var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if (contextFeature != null)
                    {
                        //logger.LogError($"Something went wrong: {contextFeature.Error}");

                        await context.Response.WriteAsync(new ErrorDetails()
                        {
                            StatusCode = context.Response.StatusCode,
                            Message = "Internal Server Error."
                        }.ToString());
                    }
                });
            });
        }
    }

I need to find a way to access these 3 info that where avaiable in .Net in .Net Core version:

filterContext.ActionContext.ActionDescriptor.ActionName;
filterContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
HttpContext.Current.Request.Url.ToString();

Is it possible ?

Caio Sant'Anna
  • 304
  • 4
  • 22
  • 2
    You need to add an `ExceptionFilterAttribute`. Check out this answer https://stackoverflow.com/a/58119145/3667938 – Kahbazi Oct 10 '19 at 18:41

1 Answers1

2

For a complete solution with registering ExceptionFilter and get request path, you could try like

  1. ExceptinoFilter

    public class ExceptinoFilter : IExceptionFilter
    {
            public void OnException(ExceptionContext context)
            {
            string controllerName = context.RouteData.Values["controller"].ToString();
            string actionName = context.RouteData.Values["action"].ToString();
            var request = context.HttpContext.Request;
            var requestUrl = request.Scheme + "://" + request.Host + request.Path;
            }
    }
    
  2. Register

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews(options => {
            options.Filters.Add(new ExceptinoFilter());
        });
    }
    
Edward
  • 28,296
  • 11
  • 76
  • 121