时间:2021-07-01 10:21:17 帮助过:15人阅读
前面的深入理解Routing章节,我们讲到了在MVC中,除了使用默认的ASP.NET 5的路由注册方式,还可以使用基于Attribute的特性(Route和HttpXXX系列方法)来定义。本章,我们将讲述一种基于Lambda表达式的强类型类型。
这种方式的基本使用示例如下:
- 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的方法。
注意,在这里获取Action的方法名,是通过委托执行该Action方法来实现的(实际上并没有执行,而是基于此获取该Action的MethodInfo)。
实现原理
在Stratup.cs
的ConfigureServices
方法中配置services的时候,我们可以对MVC站点使用的核心配置文件MvcOptions
进行配置,其中该类有一个ApplicationModelConventions
属性(List<IApplicationModelConvention
>)可以保存一个IApplicationModelConvention
接口的集合,改接口可以对MVC程序的程序模型进行管线处理,该接口的定义如下:
- 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描述信息,路由约束等等,这些信息都可以进行操作。
新的IApplicationModelConvention注册方式如下:
- services.Configure<MvcOptions>(opt =>
- {
- opts.ApplicationModelConventions.Add(new MyApplicationModelConvention());
- });
所以我们可以利用这个方法,在合适的时机对整个MVC的程序模型做响应的调整和修改,本章节中的强类型路由就是利用这个特性来实现的。
实现步骤
首先定义一个强类型的路由模型TypedRouteModel
类,该类要继承于AttributeRouteModel
,AttributeRouteModel
类是基于Attribute路由的基本模型,TypedRouteModel
类的代码如下:
- 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");
至此,整个强类型路由的功能就实现完毕了,大家在使用的时候,就多了一种选择了。
弊端(或Bug)
我们看到,在上面实现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/