<strong>一. 在RouteConfig文件中创建并注册一条简单路由:</strong>
Route myroute = new Route("{controller}/{action}", new MvcRouteHandler());
routes.Add("MyRoute", myroute);
使得可以在浏览器中通过http://localhost:xxxxx//Customer/List, 或者http://localhost:26399/Admin/Index 等形式进行访问:
其中Customer表示控制器CustomerController类,List代表该类中的List方法。
除了上述写法,还可以写为:
routes.MapRoute("MyRoute", "{controller}/{action}");
此时,RouteConfig.cs文件中的内容为:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
//Route myroute = new Route("{controller}/{action}", new MvcRouteHandler());
//routes.Add("MyRoute", myroute);
routes.MapRoute("MyRoute", "{controller}/{action}");
}
}
现在,访问默认URL时,会出现错误,因为默认的URL被表示为"~/"送给路由系统,并不满足任何片段。
<strong>二. 定义默认值</strong>
在MapRoute方法中添加:
routes.MapRoute("MyRoute", "{controller}/{action}", new { action = "Index" });
对于两片段的URL,如/Home/Index,工作原理不变,对于单片段的URL,会给action变量自动赋值Index,也就是说可以请求/Home 。
更近一步,使用:
routes.MapRoute("MyRoute", "{controller}/{action}", new { controller = "Home", action = "Index" });
此时,映射的URL匹配表为:
片段数量=0:
mydomain.com => controller = Home action = Index
片段数量=1:
mydomain.com/Customer => controller=Customer action = Index
片段数量=2:
mydomain.com/Customer/List => controller = Customer action = List
<strong>三.静态URL片段</strong>
并非所有片段都需要可变,如下:
routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" });
这个URL模式将只匹配含有3个片段的URL,第一个必须是Public。
若采用下面的方式:
routes.MapRoute("", "X{controller}/{ation}");
这条路由模式匹配的方式为:匹配两片段URL,第一个片段以X打头。此时,访问http://localhost:26399/XHome/Index 即可匹配。
以上三条路由的顺序为:
public static void RegisterRoutes(RouteCollection routes)
{
//Route myroute = new Route("{controller}/{action}", new MvcRouteHandler());
//routes.Add("MyRoute", myroute);
routes.MapRoute("", "X{controller}/{action}");
routes.MapRoute("MyRoute", "{controller}/{action}", new { controller = "Home", action = "Index" });
routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" });
}
路由系统根据最先被定义的模式来匹配输入URL,只有在不匹配的情况下,才会继续对下一条路由进行处理,直到找到匹配的一条,或者尝试完所有条目。
因此,<b>必须首先定义较为具体的路由。</b>
可以根据静态片段和默认值为特定的路由创建一个别名。如以前用的是一个ShopController,现在用HomeController代替,则:
public static void RegisterRoutes(RouteCollection routes)
{
//Route myroute = new Route("{controller}/{action}", new MvcRouteHandler());
//routes.Add("MyRoute", myroute);
routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" });
routes.MapRoute("", "X{controller}/{action}");
routes.MapRoute("MyRoute", "{controller}/{action}", new { controller = "Home", action = "Index" });
routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" });
}
第一条路由匹配模式为:两片段URL,第一个片段必须是Shop,action的值为第二个URL片段。但是该模式不含controller的可变片段,因此一定会使用默认值,即/Shop/Index会转换为/Home/Index。
更进一步:
routes.MapRoute("ShopSchema2", "Shop/OldAction", new { controller = "Home", action = "Index" });
<strong>四.定义自定义片段变量</strong>
首先注释之前的所有语句,如下:
public static void RegisterRoutes(RouteCollection routes)
{
//Route myroute = new Route("{controller}/{action}", new MvcRouteHandler());
//routes.Add("MyRoute", myroute);
//routes.MapRoute("ShopSchema2", "Shop/OldAction", new { controller = "Home", action = "Index" });
//routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" });
//routes.MapRoute("", "X{controller}/{action}");
//routes.MapRoute("MyRoute", "{controller}/{action}", new { controller = "Home", action = "Index" });
//routes.MapRoute("", "Public/{controller}/{action}", new { controller = "Home", action = "Index" });
routes.MapRoute("MyRoute", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "DefaultID" });
}
最后一条路由的URL模式定义了标准的controller和action变量,和一个id的自定义变量。将匹配0~3个片段的URL,第三个片段赋值给id,没有第三个片段时会采用默认值。
可以通过RouteData.Values属性,在Action中访问任何一个片段变量:
public ActionResult CustomVariable()
{
ViewBag.CustomVariable = RouteData.Values["id"];// 此时访问http://localhost:26399/Home/CustomVariable/Hello,CustomVariable中是Hello
return View();
}
此外,如果把Action中的参数的名称变为与URL中的变量相匹配,MVC会把URL中获得的值作为参数传递给Action方法,如:
给CustomVariable这个Action方法加上id参数:
public ActionResult CustomVariable(string id)
{
ViewBag.CustomVariable = id;
return View();
}
URL变为:http://localhost:26399/Home/CustomVariable/5
则,5被当作参数id传递给Action方法:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>The custom variable is : @ViewBag.CustomVariable</div>
</body>
</html>
此时,返回的View显示:The custom variable is : 5
<strong>4.1 定义可选URL片段</strong>
可选URL片段:用户不需要指定,但又没有指定默认值的片段。
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
这条匹配的工作模式:
片段=0:xxx.com
=>
controller = Home action = Index
片段=1:xxx.com/Customer
=>
controller = Customer action = Index
片段=2:xxx.com/Customer/List
=>
controller = Customer action = List
片段=3:xxx.com/Customer/List/All
=>
controller = Customer action = List id=All
<strong>4.2 定义可变长路由</strong>
通过制定一个全匹配的片段变量,通过*作为前缀,可以支持可变片段数。
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
工作模式为:
/:controller = Home action = Index
/Customer:controller=Customer action=Index
/Customer/List:controller=Customer action=List
/Customer/List/All:controller = Customer action = List Id=All
/Customer/List/All/Delete:controller = Customer action = List Id=All catchall = Delete
/Customer/List/All/Delete/Perm :controller = Customer action = List Id = All catchall=Delete/Perm
<strong>4.3 按命名空间区分Controller优先顺序</strong>
此时,Controllers文件夹中有一个HomeController类,假如在另一个文件夹中再创建一个HomeController类,访问时会报错:
解决方法如下:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "UrlsAndRoutes.AdditionalControllers" });
}
以上代码告诉MVC框架,先考察URLsAndRoutes.AdditionalControllers命名空间。
注意:一条路由中的命名空间具有相等优先级,若:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "UrlsAndRoutes.AdditionalControllers", "UrlsAndRoutes.Controllers" });
}
会报同样的错误。
如果希望对某个命名空间中的某个Controller优先,又需要解析另一个命名空间中的其他Controller,需要创建多条路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("AddControllerRoute", "Home/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "URLsAndRoutes.AdditionalControllers" });
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "URLsAndRoutes.Controllers" });
}
此时,若用户的第一个片段为Home,会运用第一条路由,并以AdditionalControllers文件夹中的Controller为目标。除此之外的其它请求,使用Controllers文件夹中的Controller处理。
还可以在所指定的命名空间中找不到匹配时,不在搜索其它地方,如下:
Route MyRoute = routes.MapRoute("AddControllerRoute", "Home/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "UrlsAndRoutes.AdditionalControllers" });
MyRoute.DataTokens["UseNamespaceFallback"] = false;
<strong>五.约束路由</strong>
<strong>5.1 用正则表达式约束路由</strong>
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*" },
new[] { "URLsAndRoutes.Controllers" });
}
该路由匹配controller变量值以“H”打头的URL。
注意,首先运用默认值,再检查约束。因此,若请求的URL是 / ,会把默认值“Home”运用于controller,然后再检查约束。
<strong>5.2 将一条路由约束到一组指定的值</strong>
可以使用 | 把一条路由约束到一组指定的片段变量值
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^H.*", action = "^Index$|^About$"},
new[] { "URLsAndRoutes.Controllers" });
}
这条约束允许这个路由只匹配action片段的值为“Index”或者“About”的URL。
<strong>5.3 使用HTTP方法约束路由</strong>
可以约束路由,使得它们只匹配指定的HTTP方法进行请求的URL。
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new
{
controller = "^H.*",
action = "^Index$|^About$",
httpMethod = new HttpMethodConstraint("Get")
},
new[] { "URLsAndRoutes.Controllers" });
}
上述语法中,httpMethod可以是任何名字,只要是一个HttpMethodConstraint实例即可。
也可以使用类型和值约束,如下:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new
{
controller = "^H.*",
action = "^Index$|^About$",
httpMethod = new HttpMethodConstraint("Get"),
id = new RangeRouteConstraint(10, 20)
},
new[] { "URLsAndRoutes.Controllers" });
}
这条路由使用了RangeRouteConstraint类,检查提供的片段变量的值是否是10到20中的一个有效的int类型值。
假设要确保路由将仅仅匹配包含字母字符并且至少含有6个字符的字符串值:
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new
{
controller = "^H.*",
action = "^Index$|^About$",
httpMethod = new HttpMethodConstraint("Get"),
id = new CompoundRouteConstraint(new IRouteConstraint[]
{
new AlphaRouteConstraint(),
new MinLengthRouteConstraint(6)
})
},
new[] { "URLsAndRoutes.Controllers" });