【问题标题】:Throw custome exception to filter抛出自定义异常进行过滤
【发布时间】:2021-04-08 10:05:47
【问题描述】:

我需要从过滤器发送一些状态代码,但我不知道如何传递适当的上下文异常。我看到了HttpActionExecutedContext,但不知道它在哪里,在什么命名空间中......顺便说一句,它的.net core 5,web api

   public class AuthFilter : ExceptionFilterAttribute
        {
            public override void OnException(ExceptionContext context)
            {
                if (context.Exception is CustomerDataException)
                {
    
                }
                else if (context.Exception is CustomerNotFoundException)
                {
    
                }
                else if (context.Exception is CustomerExistsException)
                { 
                
                }
            }
        }

【问题讨论】:

    标签: .net asp.net-core webapi


    【解决方案1】:

    HttpActionExecutedContext 默认在 asp.net web api 中作为ActionFilterAttribute 的参数使用。

    对于您的场景,您似乎想从 ExceptionFilter 发送状态代码,您可以执行以下操作:

    public class AuthFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var statusCode = HttpStatusCode.InternalServerError;
            if (context.Exception is CustomerDataException)
            {
                statusCode = HttpStatusCode.BadRequest;
            }
            else if (context.Exception is CustomerNotFoundException)
            {
                statusCode = HttpStatusCode.NotFound;
            }
            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.StatusCode = (int)statusCode;
            context.Result = new JsonResult(new
            {
                error = new[] { context.Exception.Message },
                statusCode = statusCode,
                stackTrace = context.Exception.StackTrace
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2017-10-17
      • 2011-10-06
      • 2011-05-30
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多