解讀ASP.NET 5 & MVC6系列教程(12):基於Lamda運算式的強型別Routing實現_自學過程

來源:互聯網
上載者:User

前面的深入理解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.csConfigureServices方法中配置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類,該類要繼承於AttributeRouteModelAttributeRouteModel類是基於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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.