【问题标题】:Why is Http code 500 returned although I catch the exception尽管我捕获了异常,但为什么返回 Http 代码 500
【发布时间】:2015-07-08 07:55:09
【问题描述】:

虽然我的 if 子句在我的提琴手中执行,但我看到 http 错误 500 而不是 404,这是为什么呢?

public class GlobalExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            if (context.Exception is ResourceNotFoundException)
            {
                context.Request.CreateErrorResponse(HttpStatusCode.NotFound, context.Exception.Message);
            }
            else
            {
                base.Handle(context); 
            }
        }
    }

这是我在提琴手响应中得到的:

HTTP/1.1 500 Internal Server Error
Content-Length: 3945
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 08 Jul 2015 08:14:45 GMT

{"Message":"An error has occurred.","ExceptionMessage":"The Resource could not be found!","ExceptionType":"ErpApplicationEndpoints.ResourceNotFoundException","StackTrace":"   at  ... Removed for clarity...

【问题讨论】:

  • 您的自定义处理程序正在执行?
  • 是的,就像我写的那样执行 if 子句!
  • 我用提琴手响应更新了我的问题。

标签: c# asp.net-web-api asp.net-web-api2


【解决方案1】:

您需要在 if 子句中的 ExceptionHandlerContext 对象上设置 Result 属性,而不是执行 CreateErrorResponse(这也是不正确的,因为您没有将创建的 HttpResponseMessage 分配给任何东西)

context.Result = <a-httpactionresult-instance-here>

【讨论】:

  • 所以要获得一个 IHttpActionResult 实例我必须在自定义类中实现这个接口?或者不应该是 this => context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, errorMessagError);
  • 啊...最后一段代码来自 ExceptionFilter !!! ExceptionHandler 没有 context.Response,只有 context.Request 或 context.Result WHY ???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 2018-10-24
  • 2013-03-15
  • 2012-02-01
  • 1970-01-01
相关资源
最近更新 更多