Add routing priority to ASP. net mvc and WebApi (1)
I. Why do I need a route priority?
We all know that we are in Asp. net MVC project or WebApi project, the registered route has no priority. when the project is large, or has multiple regions, or multiple Web projects, or is developed using a plug-in framework, our route registration is probably not written in a file, but distributed in many files of different projects. As a result, the priority of the route is highlighted.
For example: 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 "}
- );
If you first register the above general default route and then register the login route, then in any case, the first qualified route will be matched first, that is, the registration of the second route is invalid.
The reason for this problem is the order of registration of the two routes, and Asp. net MVC and WebApi do not have the concept of priority. Therefore, we need to implement this idea on our own today and add a concept of priority when registering a route.
Ii. Solution
1. Analyze the ingress of Route registration. For example, we create a project named 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);
- }
- }
There are two entry points for registering Mvc routes:
A. AreaRegistration. RegisterAllAreas (); register a region route
B. RouteConfig. RegisterRoutes (RouteTable. Routes); Register the project route
There is a WebApi route registration entry:
WebApiConfig. Register (GlobalConfiguration. Configuration); Register a WebApi route
2. Process Analysis of registered routes
AreaRegistrationContext
RouteCollection
HttpRouteCollection
When registering a route, these three classes are used to register and process the route.
3. Route Priority Scheme
A. Change the ingress of Route Registration
B. Customize the RoutePriority and HttpRoutePriority of a route. Both classes have the Priority attribute.
C. Customize a RegistrationContext to register the route. The registered object is the preceding custom route.
D. After all the routes are registered, they are added to the RouteCollection and HttpRouteCollection in priority order.