1.用正则表达式约束路由
可以用正则表达式来约束一条路由,以便对于一个URL片段,只有指定的一些值才会形成匹配。
Demo:
routes.MapRoute(
name: "ProductList",
url: "{controller}/{action}/{typeId}/{productId}",
constraints:new { typeId=@"\d{1}", productId=@"\d{4}"},//限制路由传入参数(正则表达式)
defaults: new { controller = "Home", action = "ProductList", id = UrlParameter.Optional, productId =UrlParameter.Optional}
);
这条路由只匹配typeId为0~9的1位整数,productId为4位的整数(0-9)的URL,更严格的对参数进行了限制。
我们可以根据需要对url中的所有参数(controller、action、parameter1、parameter2…parameterN)进行正则匹配。
测试:
在Home控制器添加动作方法ProductList:
public ActionResult ProductList(int? typeId,int? productId)
{
return View();
}
在对应的视图文件夹下,添加视图ProductList.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>产品列表页</title>
<style>
.ad {
width:200px;
height:200px;
background-color:#bfa;
position:absolute;
top:50px;
left:500px;
}
</style>
</head>
<body>
<div>
<p>产品列表页</p>
@*
嵌入部分页面
*@
@Html.Partial("_Ad")
</div>
</body>
</html>
没有匹配上,报错:
传入的参数已正确匹配:
下面测试后台数据的接收,由于此路由匹配两个片段(typeId和productId)
在其他的View页面,使用超链接,跳转到ProducList当前页面,并采用路由传参的方式:
<a href="/Home/ProductList/8/1596">产品列表页面</a>
匹配上了的话,后台也可以正常接收。
2.使用HTTP方法约束路由
可以对路由进行约束,以使它们只匹配以指定的HTTP方法进行请求的URL。
constraints:new { typeId=@"\d+", productId=@"\d{4}",httpMethod=new HttpMethodConstraint("GET")},//限制路由传入参数(正则表达式)
这条路由限制到GET请求。
如还要支持POST,则可以这样处理:
httpMethod = new HttpMethodConstraint("GET","POST")
3.使用类型和值约束
MVC框架包含了许多内置的约束,它们可以用来限制路由匹配基于类型和片段变量值的URL。
在System.Web.Mvc.Routing.Constraints命名空间下,包含了一些约束类,检查片段变量是不同的C#类型值,并执行基本的检查,并且这些类目前只支持ASP.NET MVC
5.2版本
使用约束类,改写上面的路由配置,
//路由约束
routes.MapRoute(
name: "ProductList",
url: "{controller}/{action}/{typeId}/{productId}",
//constraints:new { typeId=@"\d{1}", productId=@"\d{4}" },//限制路由传入参数(正则表达式)
constraints: new {
typeId = new CompoundRouteConstraint(
new IRouteConstraint[] {
new IntRouteConstraint(),//限制参数类型:int
new RangeRouteConstraint(0,9),//0~9
new LengthRouteConstraint(1)//一位数字
}
),
productId= new CompoundRouteConstraint(
new IRouteConstraint[] {
new IntRouteConstraint(),//限制参数类型:int
new LengthRouteConstraint(4)//长度为4
}
)
},
defaults: new { controller = "Home", action = "ProductList", id = UrlParameter.Optional, productId =UrlParameter.Optional}
);
分析:
使用CompoundRouteConstraint类(该类接收一个约束数组作为构造参数),可以为一个单一片段变量组合不同的约束
测试:
未匹配上:
已匹配上:
正常显示
微软官方文档说明:
ASP.NET MVC 5.2约束类