WebApi总是returnshttp状态码200时出现异常

Web Api always returns http status code 200 when an exception occurs

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {

        context.Result = new NiceInternalServerExceptionResponse("The current operation could not be completed sucessfully.);
    }
}

当调用此 Get 操作时:

        [HttpGet]
        public async Task<IHttpActionResult> Get()
        {
            Convert.ToInt16("this causes an exception state");
            var data = await service.Get();
            return Ok(data);
        }

出现异常...并触发了我的全局 exc 处理程序。

当我的自定义回复 return 发送给客户时,我的提琴手总是说:

结果:200

我也可以将 return Ok(data); 更改为 return NotFound();

这不会改变结果状态代码中的任何内容。

如何 overwrite/intercept 创建 http 状态并 return 我自己的状态代码 500?

在我的网络客户端上,我需要仅在状态代码 500 为 returned 时显示一个带有日志记录 ID + 错误消息的漂亮错误对话框。

我是这样做的...

    [HttpPost]
    public HttpResponseMessage Post()
    {
        try
        {
            // Do stuff
        }
        catch (Exception ex)
        {
            // Something went wrong - Return Status Internal Server Error
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }

对于 Get 也一样。

您可以使用下一个代码来解决自定义错误:

return Content(HttpStatusCode.NotFound, "Foo does not exist.");

您需要在 IHttpActionResult:

上设置状态码
public class NiceInternalServerExceptionResponse : IHttpActionResult
{
    public string Message { get; private set; }        
    public HttpStatusCode StatusCode { get; private set; }

    public NiceInternalServerExceptionResponse(
        string message, 
        HttpStatusCode code)
    {
        Message = message;
        StatusCode = code; 
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(StatusCode);
        response.Content = new StringContent(Message);
        return Task.FromResult(response);
    }
}

并且在你的 GlobalExceptionHandler 传递 HttpStatusCode.InternalServerError (500):

public override void Handle(ExceptionHandlerContext context)
{
    context.Result = new NiceInternalServerExceptionResponse(
        "The current operation could not be completed sucessfully.",
        HttpStatusCode.InternalServerError);
}