前面的深刻理解Routing章节,咱们讲到了在MVC中,除了使用默认的ASP.NET 5的路由注册方式,还可使用基于Attribute的特性(Route和HttpXXX系列方法)来定义。本章,咱们将讲述一种基于Lambda表达式的强类型类型。html
这种方式的基本使用示例以下:web
services.Configure<MvcOptions>(opt => { opt.EnableTypedRouting(); opt.GetRoute("homepage", c => c.Action<ProductsController>(x => x.Index())); opt.GetRoute("aboutpage/{name}", c => c.Action<ProductsController>(x => x.About(Param<string>.Any))); opt.PostRoute("sendcontact", c => c.Action<ProductsController>(x => x.Contact())); });
从示例中能够看出,咱们能够经过GetRoute或PostRoute等扩展方法来定义route,并且后面使用Lambda表达式来定Controller的类型和Action的方法。express
注意,在这里获取Action的方法名,是经过委托执行该Action方法来实现的(实际上并无执行,而是基于此获取该Action的MethodInfo)。mvc
在Stratup.cs
的ConfigureServices
方法中配置services的时候,咱们能够对MVC站点使用的核心配置文件MvcOptions
进行配置,其中该类有一个ApplicationModelConventions
属性(List<IApplicationModelConvention
>)能够保存一个IApplicationModelConvention
接口的集合,改接口能够对MVC程序的程序模型进行管线处理,该接口的定义以下:app
public interface IApplicationModelConvention { void Apply(ApplicationModel application); }
接口中的Apply
方法所接收的参数类型是ApplicationModel
,而ApplicationModel
有两个极其重要的内容能够供咱们操做,一个是Controller模型集合,一个是各类Filter的集合,该类的定义以下:优化
public class ApplicationModel { public ApplicationModel(); public IList<ControllerModel> Controllers { get; } public IList<IFilter> Filters { get; } }
这里最重要的就是ControllerModel
类,该类的实例上保存了各类各样重要而又能够操做的信息,好比该类和相关Action上的路由定义数据,API描述信息,路由约束等等,这些信息均可以进行操做。this
新的IApplicationModelConvention注册方式以下:code
services.Configure<MvcOptions>(opt => { opts.ApplicationModelConventions.Add(new MyApplicationModelConvention()); });
因此咱们能够利用这个方法,在合适的时机对整个MVC的程序模型作响应的调整和修改,本章节中的强类型路由就是利用这个特性来实现的。htm
首先定义一个强类型的路由模型TypedRouteModel
类,该类要继承于AttributeRouteModel
,AttributeRouteModel
类是基于Attribute路由的基本模型,TypedRouteModel
类的代码以下:blog
public class TypedRouteModel : AttributeRouteModel { public TypedRouteModel(string template) { Template = template; HttpMethods = new string[0]; } public TypeInfo ControllerType { get; private set; } public MethodInfo ActionMember { get; private set; } public IEnumerable<string> HttpMethods { get; private set; } public TypedRouteModel Controller<TController>() { ControllerType = typeof(TController).GetTypeInfo(); return this; } public TypedRouteModel Action<T, U>(Expression<Func<T, U>> expression) { ActionMember = GetMethodInfoInternal(expression); ControllerType = ActionMember.DeclaringType.GetTypeInfo(); return this; } public TypedRouteModel Action<T>(Expression<Action<T>> expression) { ActionMember = GetMethodInfoInternal(expression); ControllerType = ActionMember.DeclaringType.GetTypeInfo(); return this; } private static MethodInfo GetMethodInfoInternal(dynamic expression) { var method = expression.Body as MethodCallExpression; if (method != null) return method.Method; throw new ArgumentException("Expression is incorrect!"); } public TypedRouteModel WithName(string name) { Name = name; return this; } public TypedRouteModel ForHttpMethods(params string[] methods) { HttpMethods = methods; return this; } }
该类主要的功能是:定义支持传入Controller类型,支持链式调用。
而后再定义一个继承IApplicationModelConvention
接口的TypedRoutingApplicationModelConvention
类。代码以下:
public class TypedRoutingApplicationModelConvention : IApplicationModelConvention { internal static readonly Dictionary<TypeInfo, List<TypedRouteModel>> Routes = new Dictionary<TypeInfo, List<TypedRouteModel>>(); public void Apply(ApplicationModel application) { foreach (var controller in application.Controllers) { if (Routes.ContainsKey(controller.ControllerType)) { var typedRoutes = Routes[controller.ControllerType]; foreach (var route in typedRoutes) { var action = controller.Actions.FirstOrDefault(x => x.ActionMethod == route.ActionMember); if (action != null) { action.AttributeRouteModel = route; //注意这里是直接替换,会影响现有Controller上的Route特性定义的路由 foreach (var method in route.HttpMethods) { action.HttpMethods.Add(method); } } } } } } }
在该类中,保存了一个静态变量Routes,用于保存全部以Lamda表达式方式声明的路由,而后在现有的Controllers集合中进行查找及修改,而后替换AttributeRouteModel
属性,并设置响应的Http Method(若是不设置,则默认全部的方式都容许)。
在这里,咱们只是简单替换action.AttributeRouteModel
,因此会致使一些缺陷(好比一个Action只能支持一个路由路径,以最后一个为准),各位同窗能够根据本身的能力进行优化。
优化的时候,要注意Controller上的
Route
集合保存在controller.Attributes
属性上,Action上的Route集合保存在action.Attributes
属性上,能够对其进行优化。
而后,在MvcOptions上,咱们再为TypeRouteModel添加一些扩展方法以方便使用,代码以下:
public static class MvcOptionsExtensions { public static TypedRouteModel GetRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup) { return AddRoute(template, configSetup).ForHttpMethods("GET"); } public static TypedRouteModel PostRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup) { return AddRoute(template, configSetup).ForHttpMethods("POST"); } public static TypedRouteModel PutRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup) { return AddRoute(template, configSetup).ForHttpMethods("PUT"); } public static TypedRouteModel DeleteRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup) { return AddRoute(template, configSetup).ForHttpMethods("DELETE"); } public static TypedRouteModel TypedRoute(this MvcOptions opts, string template, Action<TypedRouteModel> configSetup) { return AddRoute(template, configSetup); } private static TypedRouteModel AddRoute(string template, Action<TypedRouteModel> configSetup) { var route = new TypedRouteModel(template); configSetup(route); if (TypedRoutingApplicationModelConvention.Routes.ContainsKey(route.ControllerType)) { var controllerActions = TypedRoutingApplicationModelConvention.Routes[route.ControllerType]; controllerActions.Add(route); } else { var controllerActions = new List<TypedRouteModel> { route }; TypedRoutingApplicationModelConvention.Routes.Add(route.ControllerType, controllerActions); } return route; } public static void EnableTypedRouting(this MvcOptions opts) { opts.ApplicationModelConventions.Add(new TypedRoutingApplicationModelConvention()); } }
在上述代码中,咱们添加了一个EnableTypedRouting
扩展方法,以便向MvcOptions.ApplicationModelConventions
属性上添加新的TypedRoutingApplicationModelConvention
类型示例。
其它的扩展方法则都是用于声明相关的route,你们注意,在最开头的示例中,咱们看到获取action信息的方法是经过委托调用该action方法(但没有真正调用),可是有的方法有参数,那怎么办呢?为此,咱们定于一个忽略参数的Param类,代码以下:
public static class Param<TValue> { public static TValue Any { get { return default(TValue); } } }
这样,咱们为含有参数的About方法定于路由的时候,就能够这样来定义了,代码以下:
opt.GetRoute("aboutpage/{name}", c => c.Action<HomeController>(x => x.About(Param<string>.Any)));
另外,因为TypeRouteModel里不少方法都是能够链式调用,因此咱们也能够经过这种方式为route指定一个名称,示例代码以下:
opt.GetRoute("homepage", c => c.Action<HomeController>(x => x.Index())).WithName("foo");
至此,整个强类型路由的功能就实现完毕了,你们在使用的时候,就多了一种选择了。
咱们看到,在上面实现IApplicationModelConvention
接口的时候,咱们只是简单的对action.AttributeRouteModel
进行替换,也就是说,若是你在Action上已经了Route
特性的话,他会把你的信息给你覆盖掉,从而致使你的route失效。好比,若是你定义了一个这样的自定义路由:
public class ProductsController : Controller { [Route("index")] public IActionResult Index() { return Content("Index"); } }
而后又经过Lamda表达式又定义了强类型路由,代码以下:
opt.GetRoute("homepage", c => c.Action<ProductsController>(x => x.Index()));
那么,你只能经过/homepage
开来访问,而不能经过/index
来访问了,由于它把你的Route给你覆盖掉了。
可是,上述Lamda表达式方式并无覆盖Controller上定义的Route特性定义,因此若是你在ProductsController上定义了Route特性的话,二者就会组合在一块儿,例如:
[Route("products")] public class ProductsController : Controller { public IActionResult Index() { return Content("Index"); } }
那么你的访问网址应该是/products/homepage
,而不是/homepage
。不过若是你在Lamda表达式方式里的代码,是以下这样的话:
opt.GetRoute("/homepage", c => c.Action<ProductsController>(x => x.Index()));
那你的访问网址就应该是/homepage
了,由于该路由字符是绝对路径/homepage
,而不是homepage
。
参考:http://www.strathweb.com/2015/03/strongly-typed-routing-asp-net-mvc-6-iapplicationmodelconvention/
本文已同步至目录索引:解读ASP.NET 5 & MVC6系列