zoukankan      html  css  js  c++  java
  • Asp.Net MVC及Web API框架配置会碰到的几个问题及解决方案(转)

    前言

    刚开始创建MVC与Web API的混合项目时,碰到好多问题,今天拿出来跟大家一起分享下。有朋友私信我问项目的分层及文件夹结构在我的第一篇博客中没说清楚,那么接下来我就准备从这些文件怎么分文件夹说起。问题大概有以下几点: 1、项目层的文件夹结构       2、解决MVC的Controller和Web API的Controller类名不能相同的问题       3、给MVC不同命名空间的Area的注册不同的路由       4、让Web API路由配置也支持命名空间参数       5、MVC及Web API添加身份验证及错误处理的过滤器       6、MVC添加自定义参数模型绑定ModelBinder       7、Web API添加自定义参数绑定HttpParameterBinding       8、让Web API同时支持多个Get方法

    正文

    一、项目层的文件夹结构       这里的结构谈我自己的项目仅供大家参考,不合理的地方欢迎大家指出。第一篇博客中我已经跟大家说了下框架的分层及简单说了下项目层,现在我们再仔细说下。新建MVC或Web API时微软已经给我们创建好了许多的文件夹,如App_Start放全局设置,Content放样式等、Controller放控制器类、Model数据模型、Scripts脚本、Views视图。有些人习惯了传统的三层架构(有些是N层),喜欢把Model文件夹、Controller文件夹等单独一个项目出来,我感觉是没必要,因为在不同文件夹下也算是一种分层了,单独出来最多也就是编译出来的dll是独立的,基本没有太多的区别。所以我还是从简,沿用微软分好的文件夹。先看我的截图       image_thumb[2]

    我添加了区域Areas,我的思路是最外层的Model(已删除)、Controllers、Views都只放一些共通的东西,真正的项目放在Areas中,比如上图中Mms代表我的材料管理系统,Psi是另外一个系统,Sys是我的系统管理模块。这样就可以做到多个系统在一个项目中,框架的重用性不言而喻。再具体看区域中一个项目      image_thumb[4]     这当中微软生成的文件夹只有Controllers、Models、Views。其它都是我建的,比如Common放项目共通的一些类,Reports准备放报表文件、ViewModels放Knouckoutjs的ViewModel脚本文件。      接下来再看看UI库脚本库引入的一些控件要放置在哪里。如下图

    image_thumb[6]image_thumb[7] 我把框架的css images js themes等都放置在Content下,css中放置项目样式及960gs框架,js下面core是自已定义的一些共通的js包括utils.js、common.js及easyui的knouckout绑定实现knouckout.bindings.js,其它一看就懂基本不用介绍了。  

    二、解决MVC的Controller和Web API的Controller类名不能相同的问题       回到区域下的一个项目文件夹内,在Controller中我们要创建Mvc Controller及Api Controller,假如一个收料的业务(receive)       mvc路由注册为~/{controller}/{action},我希望的访问地址应该是 ~/receive/action       api中由注册为~/api/{controller},我希望的访问地址应该是 ~/api/receive       那么问题就产生了,微软设计这个框架是通过类名去匹配的 mvc下你创建一个 receiveController继承Controller,就不能再创建一个同名的receiveController继承ApiController,这样的话mvc的访问地址和api的访问地址必须要有一个名字不能叫receive,是不是很郁闷。       通过查看微软System.Web.Http的源码,我们发现其实这个问题也很好解决,在这个DefaultHttpControllerSelector类中,微软有定义Controller的后缀,如图       image_thumb[12]

    我们只要把ApiController的后缀改成和MVC不一样,就可以解决问题了。这个字段是个静态只读的Field,我们只要把它改成ApiContrller就解决问题了。我们首先想到的肯定是反射。好吧,就这么做,在注册Api路由前添加以下代码即可完成

    1 var suffix = typeof(DefaultHttpControllerSelector).GetField("ControllerSuffix", BindingFlags.Static | BindingFlags.Public);
    2  if (suffix != null) suffix.SetValue(null, "ApiController");

    三、给MVC不同命名空间的Area的注册不同的路由 这个好办,MVC路由配置支持命名空间,新建区域时框架会自动添加{区域名}AreaRegistration.cs文件,用于注册本区域的路由      image_thumb[13]   在这个文件中的RegisterArea方法中添加以下代码即可 

    1 context.MapRoute(
    2     this.AreaName + "default",
    3     this.AreaName + "/{controller}/{action}/{id}",
    4     new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    5     new string[] { "Zephyr.Areas."+ this.AreaName + ".Controllers" }
    6 );

    其中第四个参数是命名空间参数,表示这个路由设置只在此命名空间下有效。

    四、让Web API路由配置也支持命名空间参数 让人很头疼的是Web Api路由配置竟然不支持命名空间参数,这间接让我感觉它不支持Area,微软真会开玩笑。好吧我们还是自己动手。在google上找到一篇文章http://netmvc.blogspot.com/2012/06/aspnet-mvc-4-webapi-support-areas-in.html 貌似被墙了,这里有介绍一种方法替换HttpControllerSelector服务。      我直接把我的代码贴出来,大家可以直接用,首先创建一个新的HttpControllerSelector类

     1 using System;
     2 using System.Linq;
     3 using System.Collections.Concurrent;
     4 using System.Collections.Generic;
     5 using System.Net.Http;
     6 using System.Web.Http;
     7 using System.Web.Http.Controllers;
     8 using System.Web.Http.Dispatcher;
     9 using System.Net;
    10 
    11 namespace Zephyr.Web
    12 {
    13     public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector
    14     {
    15         private const string NamespaceRouteVariableName = "namespaceName";
    16         private readonly HttpConfiguration _configuration;
    17         private readonly Lazy<ConcurrentDictionary<string, Type>> _apiControllerCache;
    18 
    19         public NamespaceHttpControllerSelector(HttpConfiguration configuration)
    20             : base(configuration)
    21         {
    22             _configuration = configuration;
    23             _apiControllerCache = new Lazy<ConcurrentDictionary<string, Type>>(
    24                 new Func<ConcurrentDictionary<string, Type>>(InitializeApiControllerCache));
    25         }
    26 
    27         private ConcurrentDictionary<string, Type> InitializeApiControllerCache()
    28         {
    29             IAssembliesResolver assembliesResolver = this._configuration.Services.GetAssembliesResolver();
    30             var types = this._configuration.Services.GetHttpControllerTypeResolver()
    31                 .GetControllerTypes(assembliesResolver).ToDictionary(t => t.FullName, t => t);
    32 
    33             return new ConcurrentDictionary<string, Type>(types);
    34         }
    35 
    36         public IEnumerable<string> GetControllerFullName(HttpRequestMessage request, string controllerName)
    37         {
    38             object namespaceName;
    39             var data = request.GetRouteData();
    40             IEnumerable<string> keys = _apiControllerCache.Value.ToDictionary<KeyValuePair<string, Type>, string, Type>(t => t.Key,
    41                     t => t.Value, StringComparer.CurrentCultureIgnoreCase).Keys.ToList();
    42 
    43             if (!data.Values.TryGetValue(NamespaceRouteVariableName, out namespaceName))
    44             {
    45                 return from k in keys
    46                        where k.EndsWith(string.Format(".{0}{1}", controllerName, 
    47                        DefaultHttpControllerSelector.ControllerSuffix), StringComparison.CurrentCultureIgnoreCase)
    48                        select k;
    49             }
    50  
    51             string[] namespaces = (string[])namespaceName;
    52             return from n in namespaces
    53                    join k in keys on string.Format("{0}.{1}{2}", n, controllerName, 
    54                    DefaultHttpControllerSelector.ControllerSuffix).ToLower() equals k.ToLower()
    55                    select k;
    56         }
    57 
    58         public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
    59         {
    60             Type type;
    61             if (request == null)
    62             {
    63                 throw new ArgumentNullException("request");
    64             }
    65             string controllerName = this.GetControllerName(request);
    66             if (string.IsNullOrEmpty(controllerName))
    67             {
    68                 throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
    69                     string.Format("No route providing a controller name was found to match request URI '{0}'", 
    70                     new object[] { request.RequestUri })));
    71             }
    72             IEnumerable<string> fullNames = GetControllerFullName(request, controllerName);
    73             if (fullNames.Count() == 0)
    74             {
    75                 throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
    76                         string.Format("No route providing a controller name was found to match request URI '{0}'", 
    77                         new object[] { request.RequestUri })));
    78             }
    79 
    80             if (this._apiControllerCache.Value.TryGetValue(fullNames.First(), out type))
    81             {
    82                 return new HttpControllerDescriptor(_configuration, controllerName, type);
    83             }
    84             throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
    85                 string.Format("No route providing a controller name was found to match request URI '{0}'", 
    86                 new object[] { request.RequestUri })));
    87         }
    88     }
    89 }

    然后在WebApiConfig类的Register中替换服务即可实现

    1 config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));

    好吧,现在看看如何使用,还是在区域的{AreaName}AreaRegistration类下的RegisterArea方法中注册Api的路由:

    1 GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    2     this.AreaName + "Api",
    3     "api/" + this.AreaName + "/{controller}/{action}/{id}",
    4     new { action = RouteParameter.Optional, id = RouteParameter.Optional, 
    5         namespaceName = new string[] { string.Format("Zephyr.Areas.{0}.Controllers",this.AreaName) } },
    6     new { action = new StartWithConstraint() }
    7 );

    第三个参数defaults中的namespaceName,上面的服务已实现支持。第四个参数constraints我在第8个问题时会讲到,这里先略过。

    五、MVC及Web API添加身份验证及错误处理的过滤器 先说身份验证的问题。无论是mvc还是api都有一个安全性的问题,未通过身份验证的人能不能访问的问题。我们新一个空项目时,默认是没有身份验证的,除非你在控制器类或者方法上面加上Authorize属性才会需要身份验证。但是我的控制器有那么多,我都要给它加上属性,多麻烦,所以我们就想到过滤器了。过滤器中加上后,控制器都不用加就相当于有这个属性了。      Mvc的就直接在FilterConfig类的RegisterGlobalFilters方法中添加以下代码即可

    1 filters.Add(new System.Web.Mvc.AuthorizeAttribute());

    Web Api的过滤器没有单独一个配置类,可以写在WebApiConfig类的Register中

    1 config.Filters.Add(new System.Web.Http.AuthorizeAttribute());

    Mvc错误处理默认有添加HandleErrorAttribute默认的过滤器,但是我们有可能要捕捉这个错误并记录系统日志那么这个过滤器就不够用了,所以我们要自定义Mvc及Web Api各自的错误处理类,下面贴出我的错误处理,MvcHandleErrorAttribute

     1 using System.Web;
     2 using System.Web.Mvc;
     3 using log4net;
     4 
     5 namespace Zephyr.Web
     6 {
     7     public class MvcHandleErrorAttribute : HandleErrorAttribute
     8     {
     9         public override void OnException(ExceptionContext filterContext)
    10         {
    11             ILog log = LogManager.GetLogger(filterContext.RequestContext.HttpContext.Request.Url.LocalPath);
    12             log.Error(filterContext.Exception);
    13             base.OnException(filterContext);
    14         }
    15     }
    16 }

    Web API的错误处理

     1 using System.Net;
     2 using System.Net.Http;
     3 using System.Web;
     4 using System.Web.Http.Filters;
     5 using log4net;
     6 
     7 namespace Zephyr.Web
     8 {
     9     public class WebApiExceptionFilter : ExceptionFilterAttribute
    10     {
    11         public override void OnException(HttpActionExecutedContext context)
    12         {
    13             ILog log = LogManager.GetLogger(HttpContext.Current.Request.Url.LocalPath);
    14             log.Error(context.Exception);
    15 
    16             var message = context.Exception.Message;
    17             if (context.Exception.InnerException != null) 
    18                 message = context.Exception.InnerException.Message;
    19 
    20             context.Response = new HttpResponseMessage() { Content = new StringContent(message) };
    21 
    22             base.OnException(context);
    23         }
    24     }
    25 }

    然后分别注册到过滤器中,在FilterConfig类的RegisterGlobalFilters方法中

    1 filters.Add(new MvcHandleErrorAttribute());

    在WebApiConfig类的Register中

    1 config.Filters.Add(new WebApiExceptionFilter());

    这样过滤器就定义好了。

    六、MVC添加自定义模型绑定ModelBinder 在MVC中,我们有可能会自定义一些自己想要接收的参数,那么可以通过ModelBinder去实现。比如我要在MVC的方法中接收JObject参数

    1 public JsonResult DoAction(dynamic request)
    2 {
    3 
    4 }

    直接这样写的话接收到的request为空值,因为JObject这个类型参数Mvc未实现,我们必须自己实现,先新建一个JObjectModelBinder类,添加如下代码实现

     1 using System.IO;
     2 using System.Web.Mvc;
     3 using Newtonsoft.Json;
     4 
     5 namespace Zephyr.Web
     6 {
     7     public class JObjectModelBinder : IModelBinder
     8     {
     9         public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    10         {
    11             var stream = controllerContext.RequestContext.HttpContext.Request.InputStream;
    12             stream.Seek(0, SeekOrigin.Begin);
    13             string json = new StreamReader(stream).ReadToEnd();
    14             return JsonConvert.DeserializeObject<dynamic>(json);
    15         }
    16     }
    17 }

    然后在MVC注册路由后面添加

    1 ModelBinders.Binders.Add(typeof(JObject), new JObjectModelBinder()); //for dynamic model binder

    添加之后,在MVC控制器中我们就可以接收JObject参数了。

    七、Web API添加自定义参数绑定HttpParameterBinding

    不知道微软搞什么鬼,Web Api的参数绑定机制跟Mvc的参数绑定有很大的不同,首先Web Api的绑定机制分两种,一种叫Model Binding,一种叫Formatters,一般情况下Model Binding用于读取query string中的值,而Formatters用于读取body中的值,这个东西要深究还有很多东西,大家有兴趣自己再去研究,我这里就简单说一下如何自定义ModelBinding,比如在Web API中我自己定义了一个叫RequestWrapper的类,我要在Api控制器中接收RequestWrapper的参数,如下

    1 public dynamic Get(RequestWrapper query)
    2 {
    3     //do something
    4 }

    那么我们要新建一个RequestWrapperParameterBinding类

     1 using System.Collections.Specialized;
     2 using System.Threading;
     3 using System.Threading.Tasks;
     4 using System.Web.Http.Controllers;
     5 using System.Web.Http.Metadata;
     6 using Zephyr.Core;
     7 
     8 namespace Zephyr.Web
     9 {
    10     public class RequestWrapperParameterBinding : HttpParameterBinding
    11     {
    12         private struct AsyncVoid { }
    13         public RequestWrapperParameterBinding(HttpParameterDescriptor desc) : base(desc) { }
    14         public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, 
    15             HttpActionContext actionContext, CancellationToken cancellationToken)
    16         {
    17             var request = System.Web.HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
    18             var requestWrapper = new RequestWrapper(new NameValueCollection(request));
    19             if (!string.IsNullOrEmpty(request["_xml"]))
    20             {
    21                 var xmlType = request["_xml"].Split('.');
    22                 var xmlPath = string.Format("~/Views/Shared/Xml/{0}.xml", xmlType[xmlType.Length – 1]);
    23                 if (xmlType.Length > 1)
    24                     xmlPath = string.Format("~/Areas/{0}/Views/Shared/Xml/{1}.xml", xmlType);
    25 
    26                 requestWrapper.LoadSettingXml(xmlPath);
    27             }
    28 
    29             SetValue(actionContext, requestWrapper);
    30 
    31             TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
    32             tcs.SetResult(default(AsyncVoid));
    33             return tcs.Task;
    34         }
    35     }
    36 }

    接下来要把这个绑定注册到绑定规则当中,还是在WebApiConfig中添加

    1 config.ParameterBindingRules.Insert(0, param => {
    2     if (param.ParameterType == typeof(RequestWrapper))
    3         return new RequestWrapperParameterBinding(param);
    4 
    5     return null;
    6 });

    此时RequestWrapper参数绑定已完成,可以使用了

    八、让Web API同时支持多个Get方法 先引用微软官方的东西把存在的问题跟大家说明白,假如Web Api在路由中注册的为

    1 routes.MapHttpRoute(
    2     name: "API Default",
    3     routeTemplate: "api/{controller}/{id}",
    4     defaults: new { id = RouteParameter.Optional }
    5 );

    然后我的控制器为

    1 public class ProductsController : ApiController
    2 {
    3     public void GetAllProducts() { }
    4     public IEnumerable<Product> GetProductById(int id) { }
    5     public HttpResponseMessage DeleteProduct(int id){ }
    6 }

    那么对应的地址请求到的方法如下 image_thumb[16]

    看到上面不知道到大家看到问题了没,如果我有两个Get方法(我再加一个GetTop10Products,这种情况很常见),而且参数也相同那么路由就没有办法区分了。有人就想到了修改路由设置,把routeTemplate:修改为"api/{controller}/{action}/{id}",没错,这样是能解决上述问题,但是你的api/products无论是Get Delete Post Input方式都无法请求到对应的方法,你必须要api/products/GetAllProducts、api/products/DeleteProduct/4 ,action名你不能省略。现在明白了问题所在了。我就是要解决这个问题。

    还记得我在写第四点的时候有提到这里,思路就是要定义一个constraints去实现:        我们先分析下uri path: api/controller/x,问题就在这里的x,它有可能代表action也有可能代表id,其实我们就是要区分这个x什么情况下代表action什么情况下代表id就可以解决问题了,我是想自己定义一系统的动词,如果你的actoin的名字是以我定义的这些动词中的一个开头,那么我认为你是action,否则认为你是id。

    好,思路说明白了,我们开始实现,先定义一个StartWithConstraint类

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.Http.Routing;
     6 
     7 namespace Zephyr.Web
     8 {
     9     /// <summary>
    10     /// 如果请求url如: api/area/controller/x  x有可能是actioin或id
    11     /// 在url中的x位置出现的是以 get put delete post开头的字符串,则当作action,否则就当作id
    12     /// 如果action为空,则把请求方法赋给action
    13     /// </summary>
    14     public class StartWithConstraint : IHttpRouteConstraint
    15     {
    16         public string[] array { get; set; }
    17         public bool match { get; set; }
    18         private string _id = "id";
    19 
    20         public StartWithConstraint(string[] startwithArray = null)
    21         {
    22             if (startwithArray == null)
    23                 startwithArray = new string[] { "GET", "PUT", "DELETE", "POST", "EDIT", "UPDATE", "AUDIT", "DOWNLOAD" };
    24 
    25             this.array = startwithArray;
    26         }
    27 
    28         public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, 
    29             IDictionary<string, object> values, HttpRouteDirection routeDirection)
    30         {
    31             if (values == null) // shouldn't ever hit this.                   
    32                 return true;
    33 
    34             if (!values.ContainsKey(parameterName) || !values.ContainsKey(_id)) // make sure the parameter is there.
    35                 return true;
    36 
    37             var action = values[parameterName].ToString().ToLower();
    38             if (string.IsNullOrEmpty(action)) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
    39             {
    40                 values[parameterName] = request.Method.ToString();
    41             }
    42             else if (string.IsNullOrEmpty(values[_id].ToString()))
    43             {
    44                 var isidstr = true;
    45                 array.ToList().ForEach(x =>
    46                 {
    47                     if (action.StartsWith(x.ToLower()))
    48                         isidstr = false;
    49                 });
    50 
    51                 if (isidstr)
    52                 {
    53                     values[_id] = values[parameterName];
    54                     values[parameterName] = request.Method.ToString();
    55                 }
    56             }
    57             return true;
    58         }
    59     }
    60 }

    然后在对应的API路由注册时,添加第四个参数constraints

    1 GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    2     this.AreaName + "Api",
    3     "api/" + this.AreaName + "/{controller}/{action}/{id}",
    4     new { action = RouteParameter.Optional, id = RouteParameter.Optional, 
    5         namespaceName = new string[] { string.Format("Zephyr.Areas.{0}.Controllers",this.AreaName) } },
    6     new { action = new StartWithConstraint() }
    7 );

    这样就实现了,Api控制器中Action的取名就要注意点就是了,不过还算是一个比较完美的解决方案。

  • 相关阅读:
    动词的形态及变化(转)
    数论基础
    P1505 [国家集训队]旅游
    贪心常见题
    主席树
    卡常火车头
    AC自动机
    左偏树
    位运算
    Linux下Vim常用操作
  • 原文地址:https://www.cnblogs.com/bosamvs/p/9304514.html
Copyright © 2011-2022 走看看