WebAPI框架里设置异常返回格式统一
Posted 杨浪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebAPI框架里设置异常返回格式统一相关的知识,希望对你有一定的参考价值。
直接上代码
1 /// <summary> 2 /// 消息代理处理,用来捕获这些特殊的异常信息 3 /// </summary> 4 public class CustomErrorMessageDelegatingHandler : DelegatingHandler 5 { 6 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 7 { 8 return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) => 9 { 10 HttpResponseMessage response = responseToCompleteTask.Result; 11 HttpError error = null; 12 if (response.TryGetContentValue<HttpError>(out error)) 13 { 14 //自定义错误处理 15 //error.Message = "这个接口调用出错了"; 16 } 17 if (error != null) 18 { //这是本人创建的一个返回类 19 var resultMsg = new ResultMsg { StatusCode = (int)StatusCodeEnum.HttpUrlEror, Info =error.MessageDetail }; 20 return new HttpResponseMessage { Content = new StringContent(resultMsg.ToJson(), 21 System.Text.Encoding.GetEncoding("UTF-8"), "application/json"), StatusCode = HttpStatusCode.OK }; 22 } 23 else 24 { 25 return response; 26 } 27 }); 28 } 29 }
然后就是注册该cs文件,找到Global.asax文件
1 protected void Application_Start() 2 { 3 AreaRegistration.RegisterAllAreas(); 4 //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 5 //RouteConfig.RegisterRoutes(RouteTable.Routes); 6 //BundleConfig.RegisterBundles(BundleTable.Bundles); 7 GlobalConfiguration.Configure(WebApiConfig.Register); 8 GlobalConfiguration.Configuration.Filters.Add(new ErrorHandler()); 9 }
最后大功告成,效果:
1 { 2 "StatusCode": 404, 3 "Info": "在控制器“StudyTask”上找不到与该请求匹配的操作。", 4 "Data": null 5 }
以上是关于WebAPI框架里设置异常返回格式统一的主要内容,如果未能解决你的问题,请参考以下文章