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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM