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 ?

1

1 Answer 1

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());
        });
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.