Add routing priority for ASP. NET MVC and WebApi

  • 2021-07-02 23:53:04
  • OfStack

1. Why do you need routing priority

Everyone knows that we have no priority in registering routes in Asp. Net MVC or WebApi projects. When the project is large, or has multiple areas, or multiple Web projects, or adopts plug-in framework development, our route registration is probably not written in one file, but scattered in many different project files, so that the problem of route priority is highlighted.

For example: in 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 Medium  
 
context.MapRoute( 
  name: "Login",  
  url: "login", 
  defaults: new { area = "Admin", controller = "Account", action = "Login", id = UrlParameter.Optional }, 
  namespaces: new string[] { "Wenku.Admin.Controllers" } 
); 

If you first register the general default route above, and then register the login route, then no matter what, you will first match the first route that meets the conditions, that is, the second route registration is invalid.
The reason for this problem is the order of registration of these two routes, and the registered routes in Asp. Net, MVC and WebApi do not have the concept of priority, so today we want to realize this idea ourselves and add the concept of priority when registering routes.

2. Solutions

1. First, analyze the entry of route registration, for example, we create a new mvc 4.0 project


public class MvcApplication : System.Web.HttpApplication 
{ 
  protected void Application_Start() 
  { 
    AreaRegistration.RegisterAllAreas(); 
 
    WebApiConfig.Register(GlobalConfiguration.Configuration); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
  } 
} 

There are two registration entries for Mvc routing:
a. AreaRegistration. RegisterAllAreas (); Register regional routing
b. RouteConfig. RegisterRoutes (RouteTable. Routes); Register project routing

There is one WebApi routing registry entry:
WebApiConfig. Register (GlobalConfiguration. Configuration); Register an WebApi route

2. Processing class analysis of registered route

AreaRegistrationContext
RouteCollection
HttpRouteCollection

When registering routes, these three classes are mainly used to register and handle routes.

3. Routing priority scheme

a, change the registration entry of the route
b, customize the structure classes RoutePriority and HttpRoutePriority of one route, both of which have the attribute Priority
c, customize 1 RegistrationContext to register the route, and the registered object is the above-mentioned custom route.
d, after all the route registration is completed, it will be added to RouteCollection and HttpRouteCollection in priority order to take effect.

3. Concrete realization

1. Route definition


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. Define the interface for routing registration


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

3. Define the routing registration context class


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. Add the route registration processing method to the Configuration class


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; 
} 
 In this way 1 Come and you're done. When you use it, you only need to use it in Global.asax.cs Modify the original registration entry in the file to 

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(); // Register custom routes  
  } 
} 
 Use only the custom route registration interface that you need to inherit in each project IRouteRegister For example: 

public class Registration : IRouteRegister 
{ 
  public void Register(RegistrationContext context) 
  { 
    // Register the back-end to manage the login route  
    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 
   ); 
 
    // Register the default route of the back-end management page  
    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 
    ); 
 
    // Register for mobile phone access WebApi Route  
    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. Summary

When encountered a large project registration route does not take effect, you should think that it may be because of the routing order. The above is the whole content of this article, hoping to inspire everyone's study.


Related articles: