1. 程式人生 > >WebAPI框架裏設置異常返回格式統一

WebAPI框架裏設置異常返回格式統一

一個 hand icon 特殊 .config routes x文件 content enc

直接上代碼

 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框架裏設置異常返回格式統一