重写的OnException过滤器始终返回状态代码500

时间:2017-04-05 12:20:34

标签: c# error-handling asp.net-web-api2

我正在尝试构建一个 FilterAttribute 来处理我的 Web API 的错误。目前它将错误记录到数据库中,但无论我做什么,它总是返回500 内部服务器错误。 我的过滤器如下所示:

public class LogExceptionFilterAttribute : ExceptionFilterAttribute
{

    // Private properties
    private readonly ILogProvider _logger;

    /// <summary>
    /// Our default constructor
    /// </summary>
    /// <param name="logger"></param>
    public LogExceptionFilterAttribute(ILogProvider logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// Invoked when an exception has been thrown
    /// </summary>
    /// <param name="context">The context</param>
    public override async void OnException(HttpActionExecutedContext context)
    {

        // Get our user
        var requestContext = context.Request.GetRequestContext();
        var user = requestContext.Principal.Identity;

        // Create our response
        var message = await _logger.ErrorAsync(context.Exception, user);
        var statusCode = GetStatusCodeFromException(context);
        var content = new HttpResponseMessage(statusCode);
        //{
        //    Content = new StringContent(message),
        //    StatusCode = statusCode
        //};

        // Assign our response to our context
        context.Response = content;
    }

    /// <summary>
    /// Gets a status code from an error
    /// </summary>
    /// <param name="context">The context</param>
    /// <returns></returns>
    private static HttpStatusCode GetStatusCodeFromException(HttpActionExecutedContext context)
    {

        // Cast the exception as an HttpException
        var exception = context.Exception as HttpException;

        // If there is still an exception, return the code
        if (exception != null)
            return (HttpStatusCode)exception.GetHttpCode();

        // Switch on the exception type
        switch (context.Exception)
        {

            // Not found
            case ObjectNotFoundException ex:
                return HttpStatusCode.NotFound;

            // Not implemented
            case NotImplementedException ex:
                return HttpStatusCode.NotImplemented;

            // Internal server error
            default:
                return HttpStatusCode.InternalServerError;
        }
    }
}

我在 GetStatusCodeFromException 方法中放置了一个断点,并验证我应该获得的实际状态代码是501(未实现),但返回值始终为500.我已尝试使用其他状态代码它也一直是500。

有人知道我怎样才能真正让它返回不同的状态代码?

更新

我发现了更多。 如果我将OnException方法更改为:

public override async void OnException(HttpActionExecutedContext context)
{

    // Get our user
    var request = context.Request;
    //var requestContext = request.GetRequestContext();
    //var user = requestContext.Principal.Identity;

    //// Log our error and get the status code
    //var message = await _logger.ErrorAsync(context.Exception, user);
    //var statusCode = GetStatusCodeFromException(context);

    // Create our response
    context.Response = request.CreateResponse(HttpStatusCode.NotImplemented);
}

使用postman时我得到了一个很好的501错误,但是当我取消注释 requestContext 行时,它会收到错误500.我认为调用 GetRequestContext 会以某种方式更改HttpRequestMessage,这样当我调用 CreateResponse 时,它总是生成500.

任何人都知道为什么?或者如何绕过它?

0 个答案:

没有答案