c# – 发生异常时,Web Api始终返回http状态代码200
发布时间:2020-12-15 22:17:55 所属栏目:百科 来源:网络整理
导读:public class GlobalExceptionHandler : ExceptionHandler{ public override void Handle(ExceptionHandlerContext context) { context.Result = new NiceInternalServerExceptionResponse("The current operation could not be completed sucessfully.); }}
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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |