MVC的URL路由规则


总结来说有6个MapRoute()的重载方法;

例一:系统的默认格式

代码如下

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

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );
          }
url格式为:http://localhost:0000/ home/index 对应规则为: {controller}/{action}/{id}黑体部分就是对应部分。这还是有默认值的情况。

详细的匹配应该为:http://localhost:0000/Custom/Detials/1

实例二:不使用默认值的Url路由规则

函数头:MapRoute(string name,string url);

routes.MapRoute("没有默认值路由规则","{controller}/{id}--{action}");

适合的Url例子:http://localhost:0000/Custom/1-Detials

它将不匹配:http://localhost:0000/

实例三带名称空间的Url路由规则

函数头:MapRoute(string name,string url,string[] namespaces);

 routes.MapRoute(
              "MyUrl", // 路由名称
              "{controller}/{id}-{action}", // 带有参数的 URL
              new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值
              new string[] { "MvcDemo.Controllers" }//命名空间
          );
Url: http://local:0000/Custom/1-Detials

这个例子是带命名空间的路由规则,这在Aeras使用时非常有用。

实例四:带约束的路由规则

函数头:MapRoute(string name,string url,object defaults,object constraints);//路由名,Url规则,默认值,名称空间

  routes.MapRoute(
                "Rule1",
                "{controller}/{action}-{Year}-{Month}-{Day}}",
                new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
                new { Year = @"^\d{4}", Month = @"\d{2}" }
            );
url:http://localhost:14039/home/index-2010-01-21

实例五:带名称空间,带约束,带默认值的路由规则

函数头:MapRoute( string name,string url, object defaults, object constraints, string[] namespaces);

routes.MapRoute(
                "Rule1",
                "Admin/{controller}/{action}-{Year}-{Month}-{Day}",
                new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
                new { Year = @"^\d{4}", Month = @"\d{2}" },
                new string[] { "MvcDemo.Controllers" }
            );
Url:http://localhost:14039/ Admin/home/index-2010-01-21
实例六:捕获所有的路由

public static void RegistRoutes(RouteCollection routes)

{

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(

"all",

"{*Vauler}",

new {controller="Home",action="Index",id=UrlParameter.Optional}

)


}


 关于Global.asax剩余部分的说明

routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 是忽略这个规则的Url

AreaRegistration.RegisterAllAreas();//注册所有的Areas

RegisterRoutes(RouteTable.Routes);//注册我们写的规则

   //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);//调试用语句,需要下载RouteDebug.dll,并添加引用!加入这句话后就可以测试Url路由了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值