你們都知道咱們在Asp.Net MVC項目或WebApi項目中註冊路由是沒有優先級的,當項目比較大、或有多個區域、或多個Web項目、或採用插件式框架開發時,咱們的路由註冊極可能不是寫在一個文件中的,而是分散在不少不一樣項目的文件中,這樣一來,路由的優先級的問題就突顯出來了。後端
好比: App_Start/RouteConfig.cs中api
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
Areas/Admin/AdminAreaRegistration.cs中mvc
context.MapRoute( name: "Login",
url: "login", defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional }, namespaces: new string[] { "Wenku.Admin.Controllers" } );
假如是先註冊上面那個通用的default路由,再註冊這個login的路由,那麼不管怎麼樣,都會先匹配第一個知足條件的路由,也就是第兩個路由註冊是無效的。
形成這個問題的緣由就是這兩個路由註冊的順序問題,而Asp.Net MVC及WebApi中註冊路由都沒有優先級這個概念,因此今天咱們就是要本身實現這個想法,在註冊路由時加入一個優先級的概念。框架
一、先分析路由註冊的入口,好比咱們新建一個mvc4.0的項目 ide
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } }
Mvc路由的註冊入口有兩個:
a. AreaRegistration.RegisterAllAreas(); 註冊區域路由
b. RouteConfig.RegisterRoutes(RouteTable.Routes); 註冊項目路由ui
WebApi路由註冊入口有一個:
WebApiConfig.Register(GlobalConfiguration.Configuration); 註冊WebApi路由this
二、註冊路由的處理類分析
AreaRegistrationContext
RouteCollection
HttpRouteCollectionurl
註冊路由時主要是由這三個類來註冊處理路由的。spa
三、路由優先級方案
a、更改路由的註冊入口
b、自定義一個路由的結構類RoutePriority及HttpRoutePriority,這兩個類下面都有Priority這個屬性
c、自定一個RegistrationContext來註冊路由,註冊的對象爲上述自定義路由。
d、全部的路由註冊完成以後再按優先順序添加到RouteCollection及HttpRouteCollection中實際生效。插件
一、路由定義
public class RoutePriority : Route { public string Name { get; set; } public int Priority { get; set; } public RoutePriority(string url, IRouteHandler routeHandler) : base(url,routeHandler) { } } public class HttpRoutePriority { public string Name { get; set; } public int Priority { get; set; } public string RouteTemplate{get;set;} public object Defaults{get;set;} public object Constraints{get;set;} public HttpMessageHandler Handler{get;set;} }
二、定義路由註冊的接口
public interface IRouteRegister { void Register(RegistrationContext context); }
三、定義路由註冊上下文類
public class RegistrationContext { #region mvc public List<RoutePriority> Routes = new List<RoutePriority>(); public RoutePriority MapRoute(string name, string url,int priority=0) { return MapRoute(name, url, (object)null /* defaults */, priority); } public RoutePriority MapRoute(string name, string url, object defaults, int priority = 0) { return MapRoute(name, url, defaults, (object)null /* constraints */, priority); } public RoutePriority MapRoute(string name, string url, object defaults, object constraints, int priority = 0) { return MapRoute(name, url, defaults, constraints, null /* namespaces */, priority); } public RoutePriority MapRoute(string name, string url, string[] namespaces, int priority = 0) { return MapRoute(name, url, (object)null /* defaults */, namespaces, priority); } public RoutePriority MapRoute(string name, string url, object defaults, string[] namespaces,int priority=0) { return MapRoute(name, url, defaults, null /* constraints */, namespaces, priority); } public RoutePriority MapRoute(string name, string url, object defaults, object constraints, string[] namespaces, int priority = 0) { var route = MapPriorityRoute(name, url, defaults, constraints, namespaces, priority); var areaName = GetAreaName(defaults); route.DataTokens["area"] = areaName; // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up // controllers belonging to other areas bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0); route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback; return route; } private static string GetAreaName(object defaults) { if (defaults != null) { var property = defaults.GetType().GetProperty("area"); if (property != null) return (string)property.GetValue(defaults, null); } return null; } private RoutePriority MapPriorityRoute(string name, string url, object defaults, object constraints, string[] namespaces,int priority) { if (url == null) { throw new ArgumentNullException("url"); } var route = new RoutePriority(url, new MvcRouteHandler()) { Name = name, Priority = priority, Defaults = CreateRouteValueDictionary(defaults), Constraints = CreateRouteValueDictionary(constraints), DataTokens = new RouteValueDictionary() }; if ((namespaces != null) && (namespaces.Length > 0)) { route.DataTokens["Namespaces"] = namespaces; } Routes.Add(route); return route; } private static RouteValueDictionary CreateRouteValueDictionary(object values) { var dictionary = values as IDictionary<string, object>; if (dictionary != null) { return new RouteValueDictionary(dictionary); } return new RouteValueDictionary(values); } #endregion #region http public List<HttpRoutePriority> HttpRoutes = new List<HttpRoutePriority>(); public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, int priority = 0) { return MapHttpRoute(name, routeTemplate, defaults: null, constraints: null, handler: null, priority: priority); } public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, int priority = 0) { return MapHttpRoute(name, routeTemplate, defaults, constraints: null, handler: null, priority: priority); } public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, object constraints, int priority = 0) { return MapHttpRoute(name, routeTemplate, defaults, constraints, handler: null, priority: priority); } public HttpRoutePriority MapHttpRoute(string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler, int priority = 0) { var httpRoute = new HttpRoutePriority(); httpRoute.Name = name; httpRoute.RouteTemplate = routeTemplate; httpRoute.Defaults = defaults; httpRoute.Constraints = constraints; httpRoute.Handler = handler; httpRoute.Priority = priority; HttpRoutes.Add(httpRoute); return httpRoute; } #endregion }
四、把路由註冊處理方法添加到Configuration類中
public static Configuration RegisterRoutePriority(this Configuration config) { var typesSoFar = new List<Type>(); var assemblies = GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) { var types = assembly.GetTypes().Where(t => typeof(IRouteRegister).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface); typesSoFar.AddRange(types); } var context = new RegistrationContext(); foreach (var type in typesSoFar) { var obj = (IRouteRegister)Activator.CreateInstance(type); obj.Register(context); } foreach (var route in context.HttpRoutes.OrderByDescending(x => x.Priority)) GlobalConfiguration.Configuration.Routes.MapHttpRoute(route.Name, route.RouteTemplate, route.Defaults, route.Constraints, route.Handler); foreach (var route in context.Routes.OrderByDescending(x => x.Priority)) RouteTable.Routes.Add(route.Name, route); return config; } private static IEnumerable<Assembly> GetReferencedAssemblies() { var assemblies = BuildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) yield return assembly; }
這樣一來就大功告成,使用時只須要在Global.asax.cs文件中修改原註冊入口爲
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); Configuration.Instance() .RegisterComponents() .RegisterRoutePriority(); //註冊自定義路由 } }
在每一個項目中使用只須要要繼承自定義路由註冊接口IRouteRegister,例如:
public class Registration : IRouteRegister { public void Register(RegistrationContext context) { //註冊後端管理登陸路由 context.MapRoute( name: "Admin_Login", url: "Admin/login", defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional }, namespaces: new string[] { "Wenku.Admin.Controllers" }, priority: 11 ); //註冊後端管理頁面默認路由 context.MapRoute( name: "Admin_default", url: "Admin/{controller}/{action}/{id}", defaults: new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "Wenku.Admin.Controllers" }, priority: 10 ); //註冊手機訪問WebApi路由 context.MapHttpRoute( name: "Mobile_Api", routeTemplate: "api/mobile/{controller}/{action}/{id}", defaults: new { area = "mobile", action = RouteParameter.Optional, id = RouteParameter.Optional, namespaceName = new string[] { "Wenku.Mobile.Http" } }, constraints: new { action = new StartWithConstraint() }, priority: 0 ); } }
4、總結
這是一個對Asp.Net Mvc的一個很小的功能拓展,小項目可能不太須要這個功能,但有時候項目大了註冊的路由不生效時你應該要想到有多是由於路由順序的緣由,這時這個路由優先級的功能有可能就會給你帶來便利。總之共享給有須要的朋友們參考。