<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        為ASP.NET MVC及WebApi添加路由優先級

        來源:懂視網 責編:小采 時間:2020-11-27 22:38:10
        文檔

        為ASP.NET MVC及WebApi添加路由優先級

        為ASP.NET MVC及WebApi添加路由優先級:一、為什么需要路由優先級 大家都知道我們在Asp.Net MVC項目或WebApi項目中注冊路由是沒有優先級的,當項目比較大、或有多個區域、或多個Web項目、或采用插件式框架開發時,我們的路由注冊很可能 不是寫在一個文件中的,而是分散在很多不同項目的文件中,這樣
        推薦度:
        導讀為ASP.NET MVC及WebApi添加路由優先級:一、為什么需要路由優先級 大家都知道我們在Asp.Net MVC項目或WebApi項目中注冊路由是沒有優先級的,當項目比較大、或有多個區域、或多個Web項目、或采用插件式框架開發時,我們的路由注冊很可能 不是寫在一個文件中的,而是分散在很多不同項目的文件中,這樣

        一、為什么需要路由優先級

        大家都知道我們在Asp.Net MVC項目或WebApi項目中注冊路由是沒有優先級的,當項目比較大、或有多個區域、或多個Web項目、或采用插件式框架開發時,我們的路由注冊很可能 不是寫在一個文件中的,而是分散在很多不同項目的文件中,這樣一來,路由的優先級的問題就突顯出來了。

        比如: App_Start/RouteConfig.cs中

        routes.MapRoute( 
         name: "Default", 
         url: "{controller}/{action}/{id}", 
         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
        ); 
         
        Areas/Admin/AdminAreaRegistration.cs中 
         
        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中注冊路由都沒有優先級這個概念,所以今天我們就是要自己實現這個想法,在注冊路由時加入一個優先級的概念。

        二、解決思路

        1、先分析路由注冊的入口,比如我們新建一個mvc4.0的項目

        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);          注冊項目路由

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

        2、注冊路由的處理類分析

        AreaRegistrationContext
        RouteCollection
        HttpRouteCollection

        注冊路由時主要是由這三個類來注冊處理路由的。

        3、路由優先級方案

        a、更改路由的注冊入口
        b、自定義一個路由的結構類RoutePriority及HttpRoutePriority,這兩個類下面都有Priority這個屬性
        c、自定一個RegistrationContext來注冊路由,注冊的對象為上述自定義路由。
        d、所有的路由注冊完成之后再按優先順序添加到RouteCollection及HttpRouteCollection中實際生效。

        三、具體實現

        1、路由定義

        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;} 
        } 
        

        2、定義路由注冊的接口

        public interface IRouteRegister 
        { 
         void Register(RegistrationContext context); 
        } 

        3、定義路由注冊上下文類

        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 
        } 
        

        4、把路由注冊處理方法添加到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 
         ); 
         } 
        } 
        
        

        四、總結

        當遇到大項目注冊的路由不生效時你應該要想到有可能是因為路由順序的原因,

        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        為ASP.NET MVC及WebApi添加路由優先級

        為ASP.NET MVC及WebApi添加路由優先級:一、為什么需要路由優先級 大家都知道我們在Asp.Net MVC項目或WebApi項目中注冊路由是沒有優先級的,當項目比較大、或有多個區域、或多個Web項目、或采用插件式框架開發時,我們的路由注冊很可能 不是寫在一個文件中的,而是分散在很多不同項目的文件中,這樣
        推薦度:
        標簽: 添加 API 路由
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 毛片a级毛片免费播放100| 国产午夜成人免费看片无遮挡 | 国产成人免费永久播放视频平台| 亚洲区小说区激情区图片区| 亚洲精品免费网站| 毛片a级三毛片免费播放| 亚洲不卡影院午夜在线观看| 在线精品免费视频无码的| 中国亚洲呦女专区| 日本一线a视频免费观看| 色妞www精品视频免费看| 亚洲一区二区精品视频| a级大片免费观看| 亚洲视频免费在线看| 亚洲性线免费观看视频成熟| 亚洲综合av一区二区三区| 在线jlzzjlzz免费播放| 四虎成人精品国产永久免费无码 | 久香草视频在线观看免费| 中文字幕人成人乱码亚洲电影| 两个人看的www免费视频中文| 久久久久久久亚洲Av无码| 无码区日韩特区永久免费系列| 亚洲精品无码久久| 国产精品亚洲玖玖玖在线观看| 成全高清在线观看免费| 亚洲欧洲精品视频在线观看| 日本成人免费在线| 国产一精品一AV一免费| 亚洲av乱码一区二区三区香蕉| 免费国内精品久久久久影院| 成人爽a毛片免费| 亚洲人精品亚洲人成在线| 免费在线观看黄网站| 91精品视频在线免费观看| 亚洲色成人四虎在线观看| 亚洲中文无韩国r级电影| 免费观看黄色的网站| 黄色免费网站在线看| 亚洲美女视频免费| 亚洲AⅤ视频一区二区三区|