码迷,mamicode.com
首页 > Windows程序 > 详细

WebAPI框架里设置异常返回格式统一

时间:2018-08-09 21:13:01      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:sys   ring   filter   custom   conf   app   ted   register   oid   

直接上代码

 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框架里设置异常返回格式统一

标签:sys   ring   filter   custom   conf   app   ted   register   oid   

原文地址:https://www.cnblogs.com/yanglang/p/9451459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!