Caio Sant'Anna
Caio Sant'Anna

Reputation: 342

Controller and Action from Global Error Handler

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 ?

Upvotes: 1

Views: 704

Answers (1)

Edward
Edward

Reputation: 29986

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());
        });
    }
    

Upvotes: 2

Related Questions