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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoyuwen08/article/details/70326865

webApi里设置全局异常返回格式

今天为了设置api返回格式统一,在网上找了一推资料,各种资料参差不齐的,最后自己捣鼓,终于弄出来了,直接上代码

    /// <summary>
    /// 消息代理处理,用来捕获这些特殊的异常信息
    /// </summary>
    public class CustomErrorMessageDelegatingHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
            {
                HttpResponseMessage response = responseToCompleteTask.Result;
                HttpError error = null;
                if (response.TryGetContentValue<HttpError>(out error))
                {
                    //自定义错误处理
                    //error.Message = "这个接口调用出错了";
                }
                if (error != null)
                {   //这是本人创建的一个返回类                 
                    var resultMsg = new ResultMsg { StatusCode = (int)StatusCodeEnum.HttpUrlEror, Info =error.MessageDetail  };
                    return new HttpResponseMessage { Content = new StringContent(resultMsg.ToJson(), 
                        System.Text.Encoding.GetEncoding("UTF-8"), "application/json"), StatusCode = HttpStatusCode.OK };
                }
                else
                {
                    return response;
                }
            });
        }
    }
然后就是注册该cs文件,找到Global.asax文件
 	protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.Filters.Add(new ErrorHandler());
        }

最后大功告成,效果:
{
  "StatusCode": 404,
  "Info": "在控制器“StudyTask”上找不到与该请求匹配的操作。",
  "Data": null
}



最后,本人技术菜鸟,有好的建议希望分享,谢谢


阅读更多
换一批

没有更多推荐了,返回首页