The main responsibility of routing is to map browser requests to the controller action of MVC.
Routing-related classes in. NET:
A route consists of two parts: Route registration and request ing:
1. Route registration:
Route registration is simple, that is, adding a route to the route table (RouteCollection:
[Csharp]
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
Routes. MapRoute (
Name: "Default ",
Url: "{controller}/{action}/{id }",
Defaults: new {controller = "Home", action = "Index", id = UrlParameter. Optional}
);
}
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
Routes. MapRoute (
Name: "Default ",
Url: "{controller}/{action}/{id }",
Defaults: new {controller = "Home", action = "Index", id = UrlParameter. Optional}
);
}
Ii. Request ing:
In ASP. net mvc, request ing is implemented through custom IHttpModule,
[Csharp]
HttpContextWrapper httpContext = new HttpContextWrapper (HttpContext. Current );
RouteData routeData = routes. GetRouteData (httpContext );
If (routeData = null)
{
Return;
}
RequestContext context = new RequestContext () {HttpContext = httpContext, RouteData = routeData };
IHttpHandler handler = routeData. RouteHandler. GetHttpHandler (context );
HttpContext. RemapHandler (handler );
HttpContextWrapper httpContext = new HttpContextWrapper (HttpContext. Current );
RouteData routeData = routes. GetRouteData (httpContext );
If (routeData = null)
{
Return;
}
RequestContext context = new RequestContext () {HttpContext = httpContext, RouteData = routeData };
IHttpHandler handler = routeData. RouteHandler. GetHttpHandler (context );
HttpContext. RemapHandler (handler );
After the route table is mapped, the returned RouteData contains information such as Controller and Action. Then, package the information and send it to HttpHandler for processing.