zoukankan      html  css  js  c++  java
  • asp.net webapi 404/或无效控制器/或无效请求 截取处理统一输出格式

    public static class PreRouteHandler
        {
            public static void HttpPreRoute(this HttpConfiguration config)
            {
                config.Services.Replace(typeof(IHttpActionInvoker), new HttpWebApiControllerActionInvoker());
                config.Services.Replace(typeof(IHttpControllerSelector), new HttpNotFoundDefaultHttpControllerSelector(config));
                config.Services.Replace(typeof(IHttpActionSelector), new HttpNotFoundControllerActionSelector());
            }
        }

        public class HttpNotFoundDefaultHttpControllerSelector : DefaultHttpControllerSelector
        {
            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
            public HttpNotFoundDefaultHttpControllerSelector(HttpConfiguration configuration)
                : base(configuration)
            {
            }
            public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
            {
                HttpControllerDescriptor decriptor = null;
                try
                {
                    decriptor = base.SelectController(request);
                }
                catch (HttpResponseException ex)
                {
                    var code = ex.Response.StatusCode;
                    var result = new OutResult() { code = OutCode.失败, msg = "无效请求" };
                    if (code == HttpStatusCode.NotFound || code == HttpStatusCode.MethodNotAllowed)
                    {
                        ex.Response.Content = new ObjectContent(typeof(OutResult), result, formatter);
                    }
                    ex.Response.StatusCode = HttpStatusCode.OK;
                    throw;
                }
                return decriptor;
            }


        }

        public class HttpNotFoundControllerActionSelector : ApiControllerActionSelector
        {
            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
            public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
            {
                HttpActionDescriptor decriptor = null;
                try
                {
                    decriptor = base.SelectAction(controllerContext);
                }
                catch (HttpResponseException ex)
                {
                    var code = ex.Response.StatusCode;
                    var result = new OutResult() { code = OutCode.失败, msg = "无效请求" };
                    if (code == HttpStatusCode.NotFound || code == HttpStatusCode.MethodNotAllowed)
                    {
                        ex.Response.Content = new ObjectContent(typeof(OutResult), result, formatter);
                    }
                    ex.Response.StatusCode = HttpStatusCode.OK;
                    throw ex;
                }
                return decriptor;
            }
        }

        public class HttpWebApiControllerActionInvoker : ApiControllerActionInvoker
        {
            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
            public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
            {
                var responseMessage = base.InvokeActionAsync(actionContext, cancellationToken);

                if (responseMessage.Exception != null)
                {
                    var baseException = responseMessage.Exception.InnerExceptions[0];
                    var result = new OutResult() { code = OutCode.失败, msg = "无效请求" };

                    if (baseException is TimeoutException)
                    {
                        result.code = OutCode.请求超时;
                        result.msg = "请求超时";
                    }

                    return Task.Run(() => new HttpResponseMessage()
                    {
                        Content = new ObjectContent(typeof(OutResult), result, formatter),
                        StatusCode = HttpStatusCode.OK
                    }, cancellationToken);
                }
                return responseMessage;
            }
        }

     

    WebApiConfig中:

     

    public static void Register(HttpConfiguration config)
            {
                GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
                GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
                GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
                    new Newtonsoft.Json.Converters.IsoDateTimeConverter()
                    {
                        DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                    }
                );

                config.Filters.Add(new OutResultAttribute());
                config.Filters.Add(new GlobalExceptionFilter());
                config.EnableCors();


                // Web API 配置和服务

                // Web API 路由
                config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

                config.HttpPreRoute();//此处新增
    }

  • 相关阅读:
    令人眼花缭乱的XP封面:)
    GT3.9.5中新增的DRS服务
    4月12日后WinXP系统将会强制下载SP2(zz)
    全球手机排名出炉 摩托三星西门子位置调整(zz)
    元宵佳节,悬谜竞猜
    Laszlo平台简介(zz)
    笔记本市场见闻
    最近Wallop好像较难上去啊
    Dell再次表示不采用AMD处理器(zz)
    Media Player Classic 6.4.8.3发布(zz)
  • 原文地址:https://www.cnblogs.com/94cool/p/6876970.html
Copyright © 2011-2022 走看看