• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
无忧岛主
实践是检验真理的唯一标准
博客园    首页    新随笔       管理    订阅  订阅
MVC之URL路由

注册路由规则集合

一个 Web 应用具有一个全局的路由表,该路由表通过 System. Web.Routing.RouteTable
的静态只读属性 Routes 表示,该属性返回一个类型为 System. Web.Routing.RouteCollection
集合

Global.asax是程序的入口,在添加的 Globa l. asax 文件中,我们将路由注册操作定义在 App lication_ Start 方法。

 

 protected void Application_Start()
        {
            //注册区域
            AreaRegistration.RegisterAllAreas();
            //注册筛选器
            RegisterGlobalFilters(GlobalFilters.Filters);
            //注册路由规则
            RegisterRoutes(RouteTable.Routes);
        }

路由规则的定义

路由规则应用层代码

上面RegisterRoutes(RouteTable.Routes);便是注册路由的操作。参数RouteTable.Routes构造了一个路由容器。下列的RegisterRoutes方法是对这个容器添加路由映射机制

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            string url = ConfigurationManager.AppSettings["VirtualPath"] + "{0}" + ConfigurationManager.AppSettings["FileExtension"] ?? ".html";

            //分类列表页面
            routes.MapRoute("Class", string.Format(url, "class/{show}-{typeid}-{page}-{parid}"), new { controller = "Home", action = "Class", show = "all", typeid = "0", page = "1", parid = "0" }, new { show = "(solute)|(wait)|(noanswer)|(all)|(overdue)", typeid = "\\d+", page = "\\d+" });
//详细页面
            routes.MapRoute("Detail", string.Format(url, "detail/{id}"), new { controller = "Home", action = "Detail" }, new { id = "\\d+" });
  //首页
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

            //错误页面
            routes.MapRoute(
            "Error",
            "error.shtml",
            new { controller = "Shared", action = "Error" }
            );
        }
RegisterRoutes(RouteCollection routes)路由规则的定义和添加

路由的注册是自上而下优先匹配原则。

如果Default放在你定义的其他路由之前,并且其他路由也满足{controller}/{action}/{id},那么路由将会报错。比如

 

routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
           new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );

 routes.MapRoute(
                "ProductDetailPage",
                string.Format(url, "Group/{productID}"),
                //"group/{productID}.html",
                new { controller = "Detail", action = "Index", productID = 794433 },
                new { productID = @"\d+" }

                );
routes.MapRoute(
                "SearchPage",//Route name
               string.Format(url, "Group/{cityID}/{productType}/{currentPageIndex}"),//URL with parameters
               new { controller = "Group", action = "Index", cityID = "17", productType = "1", currentPageIndex = 1 }

                );

比如Default默认的路由的规则(一般用于首页)它的规则的是控制器/方法/参数。而我定义一个产品详情页ProductDetailPage 虽然它映射的地址不一样,但是它的定义路由规则也是控制器/方法/参数。

按照自上而下的匹配规则,那么他匹配的就是Default而不是ProductDetailPage 。但由于从请求传过来的参数是ProductDetailPage 定义的productID而不是Default定义的参数id所以就会“/”应用程序中的服务器错误,无法找到资源。的错误。

而SearchPage这个路由规则是控制器/方法/参数1/参数2/参数3,参数的个数和Default不一样。所以认为路由规则不一样。

路由规则添加的底层源码

 public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
            Route item = new Route(url, new MvcRouteHandler()) {
                Defaults = new RouteValueDictionary(defaults),
                Constraints = new RouteValueDictionary(constraints),
                DataTokens = new RouteValueDictionary()
            };
            if ((namespaces != null) && (namespaces.Length > 0))
            {
                item.DataTokens["Namespaces"] = namespaces;
            }
            routes.Add(name, item);
            return item;
        }

从上面可以看出路由规则是由name和Route这样的一对键值对组成的。

Route又提供了两个参数和三个属性

参数:所要映射的URL地址和MVCRouteHandle路由处理程序。

而MVCRouteHandle其类型为具有如下定义的System.Web.Routing .I RouteHandler 接口。
IRouteHandler 接口在整个 URL 路由系统中具有重要的地位,其重要作用在于提供最终用于处理请求的 Handler 对象(通过调用其GetHttpHandler 方法获取)

属性

default(默认值),Contrant(约束),和DataTokens 三个属性,它们都是一个具有如下定义的类型为
System.Web.Routing.RouteValueDictionary 的对象。 Route ValueDictionary 是一个用于保存路由
变量的字典,其 Key Value 分别表示变量的名称和值。






 

 

 

 

 

 

 



 

如果本文引用了你的文章而未注明,请及时联系我。
posted on 2015-05-19 17:09  无忧岛主  阅读(1000)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3