欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

为ASP.NET MVC及WebApi添加路由优先级

程序员文章站 2024-02-13 12:56:10
一、为什么需要路由优先级 大家都知道我们在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 
    ); 
  } 
} 

四、总结

当遇到大项目注册的路由不生效时你应该要想到有可能是因为路由顺序的原因,以上就是本文的全部内容,希望对大家的学习有所启发。