微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 发生异常时,Web Api始终返回http状态代码200

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处理程序.

当我的自定义响应返回给客户端时,我的提琴手总是说:

结果:200

我也可以改变返回Ok(数据);返回NotFound();

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

如何覆盖/拦截http状态创建并返回我自己的状态代码500?

在我的Web客户端上,我需要显示一个带有日志记录ID错误消息的错误对话框,仅在返回状态代码500时.

解决方法

您需要在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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐