当前位置:编程学习 > asp >>

ASP.NET MVC——路由

路由的主要责任是将来自浏览器的请求映射到MVC的controller action。

.NET中路由相关的类如图所示:

 

 \

 


路由主要体现在两部分:路由注册和请求映射:

 

一、路由注册:

路由注册比较简单,就是向路由表(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 }
            );
        }


 

二、请求映射:

在ASP.NET MVC中,请求映射是通过自定义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);

路由表映射后返回的RouteData包含了Controller,Action等相关信息。然后将这些信息包装起来,交给HttpHandler来进行处理。

 

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,