zoukankan      html  css  js  c++  java
  • MVC路由

    以下方法的重载
    MapRoute( string name, string url);
    MapRoute( string name, string url, object defaults);
    MapRoute( string name, string url, string[] namespaces);
    MapRoute( string name, string url, object defaults, object constraints); MapRoute( string name, string url, object defaults, string[] namespaces);
    MapRoute( string name, string url, object defaults, object constraints, string[] namespaces);

    约束
    constraints参数:
    用来限定每个参数的规则或Http请求的类型.constraints属性是一个RouteValueDictionary对象,也就是一个字典表, 但是这个字典表的值可以有两种:
    用于定义正则表达式的字符串。正则表达式不区分大小写。
    一个用于实现 IRouteConstraint 接口且包含 Match 方法的对象。
    通过使用正则表达式可以规定参数格式,比如controller参数只能为4位数字:
    new { controller = @"d{4}"}
    通过第IRouteConstraint 接口目前可以限制请求的类型.因为System.Web.Routing中提供了HttpMethodConstraint类, 这个类实现了IRouteConstraint 接口. 我们可以通过为RouteValueDictionary字典对象添加键为"httpMethod", 值为一个HttpMethodConstraint对象来为路由规则添加HTTP 谓词的限制, 比如限制一条路由规则只能处理GET请求:
    httpMethod = new HttpMethodConstraint( "GET", "POST" ) 完整的代码如下:
    routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new { controller = @"d{4}" , httpMethod = new HttpMethodConstraint( "GET", "POST" ) } );

    对于一个网站,为了SEO友好,一个网址的URL层次不要超过三层:
    localhost/{频道}/{具体网页}
    其中域名第一层, 频道第二层, 那么最后的网页就只剩下最后一层了. 如果使用默认实例中的“{controller}/{action}-{其他参数}"的形式会影响网站的SEO.

    实例

    region 酒店频道部分 // hotels/list-beijing-100,200-3

    routes.MapRoute( "酒店列表页", "hotels/{action}-{city}-{price}-{star}", new { controller = "Hotel", action = "list", city = "beijing", price="-1,-1", star="-1" }, new { city=@"[a-zA-Z]",price=@"(d)+,(d)+", star="[-1-5]"} ); //hotels/所有匹配
    routes.MapRoute( "酒店首页", "hotels/{
    values}", new { controller = "Hotel", action = "default", hotelid = "" } );

    endregion //网站首页.

      routes.MapRoute( "网站首页", "{*values}", new { controller = "Home", action = "index"} ); }
    

    实现的功能:
    (1)访问 localhost/hotels/list-beijing-100,200-3 会访问酒店频道的列表页,并传入查询参数
    (2)访问 localhost/hotels 下面的任何其他页面地址, 都会跳转到酒店首页.
    (3)访问 localhost 下面的任何地址, 如果未匹配上面2条, 则跳转到首页.
    简单总结:
    (1)Routing规则有顺序(按照添加是的顺序), 如果一个url匹配了多个Routing规则, 则按照第一个匹配的Routing规则执行.
    (2)由于上面的规则, 要将具体频道的具体页面放在最上方, 将频道首页 和 网站首页 放在最下方.
    (3) {*values} 表示后面可以使任意的格式.

  • 相关阅读:
    #动态规划 0-1背包问题空间复杂度优化
    #动态规划 0-1背包问题思路概述
    #动态规划 LeetCode 337 打家劫舍 III
    #动态规划 LeetCode 213 打家劫舍 II
    #动态规划 LeetCode 198 打家劫舍
    #动态规划 LeetCode 63 不同路径 II
    #动态规划 LeetCode 62 不同路径
    #动态规划 LeetCode 279 完全平方数
    #动态规划 LeetCode 343 整数拆分
    #动态规划 LeetCode 64 最小路径和
  • 原文地址:https://www.cnblogs.com/poli/p/4353628.html
Copyright © 2011-2022 走看看