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();
解决方法
您需要在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] 举报,一经查实,本站将立刻删除。