zoukankan      html  css  js  c++  java
  • web api control注册及重写DefaultHttpControllerSelector、ApiControllerActionSelector、ApiControllerActionInvoker(转)

    出处:http://www.cnblogs.com/kingCpp/p/4651154.html

    复制代码
    namespace EWorkpal.WebApi
    {
        public class HttpNotFoundDefaultHttpControllerSelector : DefaultHttpControllerSelector
        {
            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 EWorkResultInfo<object> { Code = 10006, Entity = ex.Response.Content.ReadAsAsync<object>().Result };
                    if (code == HttpStatusCode.NotFound || code == HttpStatusCode.MethodNotAllowed)
                    {
                        ex.Response.Content = new ObjectContent(typeof(EWorkResultInfo), result, GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                    }
                    throw;
                }
                return decriptor;
            }
    
    
        }
    
        public class HttpNotFoundControllerActionSelector : ApiControllerActionSelector
        {
            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 EWorkResultInfo<object> { Code = 10006, Entity = ex.Response.Content.ReadAsAsync<object>().Result };
                    if (code == HttpStatusCode.NotFound || code == HttpStatusCode.MethodNotAllowed)
                    {
                        ex.Response.Content = new ObjectContent(typeof(EWorkResultInfo), result, GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                    }
                    throw;
                }
                return decriptor;
            }
        }
    
        public class CustomApiControllerActionInvoker : ApiControllerActionInvoker
        {
            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 EWorkResultInfo<object>
                    {
                        Message = baseException.Message, //"服务器内部错误",
                        Code = 10001,
                        Entity = responseMessage.Exception
                    };
    
                    if (baseException is TimeoutException)
                    {
                        result.Code = 10004;
                        //result.Message = "任务超时";
                    }
    
                    return Task.Run(() => new HttpResponseMessage()
                    {
                        Content = new ObjectContent(typeof(EWorkResultInfo<object>), result, GlobalConfiguration.Configuration.Formatters.JsonFormatter)
                    }, cancellationToken);
                }
                return responseMessage;
            }
        } 
    }
    复制代码

    webapi.config

    复制代码
    public static class WebApiConfig
        {
            /// <summary>
            /// 
            /// </summary>
            /// <param name="config"></param>
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
                config.Filters.Add(new EWorkAuthorize());
                config.Filters.Add(new ModelValidationFilterAttribute());
                config.Services.Replace(typeof(IHttpActionInvoker), new CustomApiControllerActionInvoker());  
                config.Services.Replace(typeof(IHttpControllerSelector), new HttpNotFoundDefaultHttpControllerSelector(config));
                config.Services.Replace(typeof(IHttpActionSelector), new HttpNotFoundControllerActionSelector());
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}"//,//{id}
                    //defaults: new { id = RouteParameter.Optional }
                );
    
                var xmlFormatter = config.Formatters.FirstOrDefault(m => m is XmlMediaTypeFormatter);
                config.Formatters.Remove(xmlFormatter);
    
                config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd hh:mm";
                
            }
        }
    复制代码

    global注册

    GlobalConfiguration.Configure(WebApiConfig.Register);
  • 相关阅读:
    [Codeforces Round #516][Codeforces 1063C/1064E. Dwarves, Hats and Extrasensory Abilities]
    接入gitment为hexo添加评论功能
    常用SQL语句
    小米前端二面面经
    将hexo的评论系统由gitment改为Valine
    同步与异步
    前端构建工具对比
    前端向后台发送请求有哪些方式
    关于hexo markdown添加的图片在github page中无法显示的问题
    使用TensorBoard可视化工具
  • 原文地址:https://www.cnblogs.com/smileberry/p/7093331.html
Copyright © 2011-2022 走看看