日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
給ASP.NETMVC及WebApi添加路由優(yōu)先級(jí)

一、為什么需要路由優(yōu)先級(jí)

創(chuàng)新互聯(lián)是一家專業(yè)提供聶拉木企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、網(wǎng)站制作、H5網(wǎng)站設(shè)計(jì)、小程序制作等業(yè)務(wù)。10年已為聶拉木眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。

大家都知道我們?cè)贏sp.Net MVC項(xiàng)目或WebApi項(xiàng)目中注冊(cè)路由是沒(méi)有優(yōu)先級(jí)的,當(dāng)項(xiàng)目比較大、或有多個(gè)區(qū)域、或多個(gè)Web項(xiàng)目、或采用插件式框架開(kāi)發(fā)時(shí),我們的路由注冊(cè)很可能 不是寫(xiě)在一個(gè)文件中的,而是分散在很多不同項(xiàng)目的文件中,這樣一來(lái),路由的優(yōu)先級(jí)的問(wèn)題就突顯出來(lái)了。

比如: App_Start/RouteConfig.cs中

 
 
  1. routes.MapRoute( 
  2.     name: "Default", 
  3.     url: "{controller}/{action}/{id}", 
  4.     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
  5. ); 
  6.  
  7. Areas/Admin/AdminAreaRegistration.cs中 
  8.  
  9. context.MapRoute( 
  10.     name: "Login",    
  11.     url: "login", 
  12.     defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional }, 
  13.     namespaces: new string[] { "Wenku.Admin.Controllers" } 
  14. ); 

假如是先注冊(cè)上面那個(gè)通用的default路由,再注冊(cè)這個(gè)login的路由,那么無(wú)論怎么樣,都會(huì)先匹配***個(gè)滿足條件的路由,也就是第兩個(gè)路由注冊(cè)是無(wú)效的。
造成這個(gè)問(wèn)題的原因就是這兩個(gè)路由注冊(cè)的順序問(wèn)題,而Asp.Net MVC及WebApi中注冊(cè)路由都沒(méi)有優(yōu)先級(jí)這個(gè)概念,所以今天我們就是要自己實(shí)現(xiàn)這個(gè)想法,在注冊(cè)路由時(shí)加入一個(gè)優(yōu)先級(jí)的概念。

二、解決思路

1、先分析路由注冊(cè)的入口,比如我們新建一個(gè)mvc4.0的項(xiàng)目

 

 
 
  1. public class MvcApplication : System.Web.HttpApplication 
  2.     protected void Application_Start() 
  3.     { 
  4.         AreaRegistration.RegisterAllAreas(); 
  5.  
  6.         WebApiConfig.Register(GlobalConfiguration.Configuration); 
  7.         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
  8.         RouteConfig.RegisterRoutes(RouteTable.Routes); 
  9.     } 

Mvc路由的注冊(cè)入口有兩個(gè):
a. AreaRegistration.RegisterAllAreas();                            注冊(cè)區(qū)域路由
b. RouteConfig.RegisterRoutes(RouteTable.Routes);          注冊(cè)項(xiàng)目路由

WebApi路由注冊(cè)入口有一個(gè):
WebApiConfig.Register(GlobalConfiguration.Configuration);  注冊(cè)WebApi路由

2、注冊(cè)路由的處理類(lèi)分析

AreaRegistrationContext
RouteCollection
HttpRouteCollection

注冊(cè)路由時(shí)主要是由這三個(gè)類(lèi)來(lái)注冊(cè)處理路由的。

3、路由優(yōu)先級(jí)方案

a、更改路由的注冊(cè)入口
b、自定義一個(gè)路由的結(jié)構(gòu)類(lèi)RoutePriority及HttpRoutePriority,這兩個(gè)類(lèi)下面都有Priority這個(gè)屬性
c、自定一個(gè)RegistrationContext來(lái)注冊(cè)路由,注冊(cè)的對(duì)象為上述自定義路由。
d、所有的路由注冊(cè)完成之后再按優(yōu)先順序添加到RouteCollection及HttpRouteCollection中實(shí)際生效。

#p#

三、具體實(shí)現(xiàn)

1、路由定義

 
 
  1. public class RoutePriority : Route 
  2.     public string Name { get; set; } 
  3.     public int Priority { get; set; } 
  4.  
  5.     public RoutePriority(string url, IRouteHandler routeHandler) 
  6.         : base(url,routeHandler) 
  7.     { 
  8.  
  9.     } 
  10.  
  11. public class HttpRoutePriority 
  12.     public string Name { get; set; } 
  13.     public int Priority { get; set; } 
  14.     public string RouteTemplate{get;set;} 
  15.     public object Defaults{get;set;} 
  16.     public object Constraints{get;set;} 
  17.     public HttpMessageHandler Handler{get;set;} 

2、定義路由注冊(cè)的接口

  
 
  1. public interface IRouteRegister 
  2.     void Register(RegistrationContext context); 

3、定義路由注冊(cè)上下文類(lèi)

 
 
  1. public class RegistrationContext 
  2.     #region mvc 
  3.     public List Routes = new List(); 
  4.  
  5.     public RoutePriority MapRoute(string name, string url,int priority=0) 
  6.     { 
  7.         return MapRoute(name, url, (object)null /* defaults */, priority); 
  8.     } 
  9.  
  10.     public RoutePriority MapRoute(string name, string url, object defaults, int priority = 0) 
  11.     { 
  12.         return MapRoute(name, url, defaults, (object)null /* constraints */, priority); 
  13.     } 
  14.  
  15.     public RoutePriority MapRoute(string name, string url, object defaults, object constraints, int priority = 0) 
  16.     { 
  17.         return MapRoute(name, url, defaults, constraints, null /* namespaces */, priority); 
  18.     } 
  19.  
  20.     public RoutePriority MapRoute(string name, string url, string[] namespaces, int priority = 0) 
  21.     { 
  22.         return MapRoute(name, url, (object)null /* defaults */, namespaces, priority); 
  23.     } 
  24.  
  25.     public RoutePriority MapRoute(string name, string url, object defaults, string[] namespaces,int priority=0) 
  26.     { 
  27.         return MapRoute(name, url, defaults, null /* constraints */, namespaces, priority); 
  28.     } 
  29.  
  30.     public RoutePriority MapRoute(string name, string url, object defaults, object constraints, string[] namespaces, int priority = 0) 
  31.     { 
  32.         var route = MapPriorityRoute(name, url, defaults, constraints, namespaces, priority); 
  33.         var areaName = GetAreaName(defaults); 
  34.         route.DataTokens["area"] = areaName; 
  35.  
  36.         // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up 
  37.         // controllers belonging to other areas 
  38.         bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0); 
  39.         route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback; 
  40.  
  41.         return route; 
  42.     } 
  43.  
  44.     private static string GetAreaName(object defaults) 
  45.     { 
  46.         if (defaults != null) 
  47.         { 
  48.             var property = defaults.GetType().GetProperty("area"); 
  49.             if (property != null) 
  50.                 return (string)property.GetValue(defaults, null); 
  51.         } 
  52.  
  53.         return null; 
  54.     } 
  55.  
  56.     private RoutePriority MapPriorityRoute(string name, string url, object defaults, object constraints, string[] namespaces,int priority) 
  57.     { 
  58.         if (url == null) 
  59.         { 
  60.             throw new ArgumentNullException("url"); 
  61.         } 
  62.  
  63.         var route = new RoutePriority(url, new MvcRouteHandler()) 
  64.         { 
  65.             Name = name, 
  66.             Priority = priority, 
  67.             Defaults = CreateRouteValueDictionary(defaults), 
  68.             Constraints = CreateRouteValueDictionary(constraints), 
  69.             DataTokens = new RouteValueDictionary() 
  70.         }; 
  71.  
  72.         if ((namespaces != null) && (namespaces.Length > 0)) 
  73.         { 
  74.             route.DataTokens["Namespaces"] = namespaces; 
  75.         } 
  76.  
  77.         Routes.Add(route); 
  78.         return route; 
  79.     } 
  80.  
  81.     private static RouteValueDictionary CreateRouteValueDictionary(object values) 
  82.     { 
  83.         var dictionary = values as IDictionary
  84.         if (dictionary != null) 
  85.         { 
  86.             return new RouteValueDictionary(dictionary); 
  87.         } 
  88.  
  89.         return new RouteValueDictionary(values); 
  90.     } 
  91.     #endregion 
  92.  
  93.     #region http 
  94.     public List HttpRoutes = new List(); 
  95.  
  96.     public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, int priority = 0) 
  97.     { 
  98.         return MapHttpRoute(name, routeTemplate, defaults: null, constraints: null, handler: null, priority: priority); 
  99.     } 
  100.  
  101.     public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, int priority = 0) 
  102.     { 
  103.         return MapHttpRoute(name, routeTemplate, defaults, constraints: null, handler: null, priority: priority); 
  104.     } 
  105.  
  106.     public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, object constraints, int priority = 0) 
  107.     { 
  108.         return MapHttpRoute(name, routeTemplate, defaults, constraints, handler: null, priority: priority); 
  109.     } 
  110.  
  111.     public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler, int priority = 0) 
  112.     { 
  113.         var httpRoute = new HttpRoutePriority(); 
  114.         httpRoute.Name = name; 
  115.         httpRoute.RouteTemplate = routeTemplate; 
  116.         httpRoute.Defaults = defaults; 
  117.         httpRoute.Constraints = constraints; 
  118.         httpRoute.Handler = handler; 
  119.         httpRoute.Priority = priority; 
  120.         HttpRoutes.Add(httpRoute); 
  121.  
  122.         return httpRoute; 
  123.     } 
  124.     #endregion 

4、把路由注冊(cè)處理方法添加到Configuration類(lèi)中

 
 
  1. public static Configuration RegisterRoutePriority(this Configuration config) 
  2.     var typesSoFar = new List(); 
  3.     var assemblies = GetReferencedAssemblies(); 
  4.     foreach (Assembly assembly in assemblies) 
  5.     { 
  6.         var types = assembly.GetTypes().Where(t => typeof(IRouteRegister).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface); 
  7.         typesSoFar.AddRange(types); 
  8.     } 
  9.  
  10.     var context = new RegistrationContext(); 
  11.     foreach (var type in typesSoFar) 
  12.     { 
  13.         var obj = (IRouteRegister)Activator.CreateInstance(type); 
  14.         obj.Register(context); 
  15.     } 
  16.  
  17.     foreach (var route in context.HttpRoutes.OrderByDescending(x => x.Priority)) 
  18.         GlobalConfiguration.Configuration.Routes.MapHttpRoute(route.Name, route.RouteTemplate, route.Defaults, route.Constraints, route.Handler); 
  19.  
  20.     foreach (var route in context.Routes.OrderByDescending(x => x.Priority)) 
  21.         RouteTable.Routes.Add(route.Name, route); 
  22.  
  23.     return config; 
  24.  
  25. private static IEnumerable GetReferencedAssemblies() 
  26.     var assemblies = BuildManager.GetReferencedAssemblies(); 
  27.     foreach (Assembly assembly in assemblies) 
  28.         yield return assembly; 

這樣一來(lái)就大功告成,使用時(shí)只需要在Global.asax.cs文件中修改原注冊(cè)入口為

 
 
  1. public class MvcApplication : System.Web.HttpApplication 
  2.     protected void Application_Start() 
  3.     { 
  4.         WebApiConfig.Register(GlobalConfiguration.Configuration); 
  5.         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
  6.         RouteConfig.RegisterRoutes(RouteTable.Routes); 
  7.  
  8.         Configuration.Instance() 
  9.             .RegisterComponents() 
  10.             .RegisterRoutePriority(); //注冊(cè)自定義路由 
  11.     } 

在每個(gè)項(xiàng)目中使用只需要要繼承自定義路由注冊(cè)接口IRouteRegister,例如:

 
 
  1. public class Registration : IRouteRegister 
  2.     public void Register(RegistrationContext context) 
  3.     { 
  4.        //注冊(cè)后端管理登錄路由 
  5.         context.MapRoute( 
  6.           name: "Admin_Login", 
  7.           url: "Admin/login", 
  8.           defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional }, 
  9.           namespaces: new string[] { "Wenku.Admin.Controllers" }, 
  10.           priority: 11 
  11.       ); 
  12.  
  13.        //注冊(cè)后端管理頁(yè)面默認(rèn)路由 
  14.         context.MapRoute( 
  15.             name: "Admin_default", 
  16.             url: "Admin/{controller}/{action}/{id}", 
  17.             defaults: new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, 
  18.             namespaces: new string[] { "Wenku.Admin.Controllers" }, 
  19.             priority: 10 
  20.         ); 
  21.  
  22.        //注冊(cè)手機(jī)訪問(wèn)WebApi路由 
  23.         context.MapHttpRoute( 
  24.             name: "Mobile_Api", 
  25.             routeTemplate: "api/mobile/{controller}/{action}/{id}", 
  26.             defaults: new 
  27.             { 
  28.                 area = "mobile", 
  29.                 action = RouteParameter.Optional, 
  30.                 id = RouteParameter.Optional, 
  31.                 namespaceName = new string[] { "Wenku.Mobile.Http" } 
  32.             }, 
  33.             constraints: new { action = new StartWithConstraint() }, 
  34.             priority: 0 
  35.         ); 
  36.     } 

四、總結(jié)

這是一個(gè)對(duì)Asp.Net Mvc的一個(gè)很小的功能拓展,小項(xiàng)目可能不太需要這個(gè)功能,但有時(shí)候項(xiàng)目大了注冊(cè)的路由不生效時(shí)你應(yīng)該要想到有可能是因?yàn)槁酚身樞虻脑?,這時(shí)這個(gè)路由優(yōu)先級(jí)的功能有可能就會(huì)給你帶來(lái)便利。總之共享給有需要的朋友們參考。


分享題目:給ASP.NETMVC及WebApi添加路由優(yōu)先級(jí)
網(wǎng)站地址:http://www.5511xx.com/article/codpjse.html