全局错误处理程序的控制器和操作

时间:2019-10-10 18:19:54

标签: asp.net-core error-handling asp.net-core-webapi

我正在将Web API从.Net迁移到.NetCore。

我们有一个自定义的ExceptionFilterAttribute来集中处理错误。像这样:

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

通过一些搜索,我设法在.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());
                    }
                });
            });
        }
    }

我需要找到一种方法来访问.Net Core版本中.Net中可用的这3个信息:

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

有可能吗?

1 个答案:

答案 0 :(得分:1)

对于注册ExceptionFilter并获取请求路径的完整解决方案,您可以尝试

  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. 注册

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews(options => {
            options.Filters.Add(new ExceptinoFilter());
        });
    }