Bar*_*xto 2 asp.net-mvc-routing asp.net-mvc-4
有这个默认路由:
routes.MapRoute(
name: "Default", // Route name
url: "{controller}/{action}/{id}", // URL with parameters
defaults: new { controller = "Application", action = "Index", id = 0 }, // Parameter defaults
constraints: new {id = @"\d+"}
);
Run Code Online (Sandbox Code Playgroud)
约束工作正常,但 id 是控制器上的 int 。因此,如果我传递的/Controller/Action/2147483648是有效的 \d+ 正则表达式,但它不是有效的Int32,则返回 500 服务器错误,我希望它进行限制,以便返回404.
如何设置约束,使其只允许有效的正整数值?哪些来自0 to 2,147,483,647?
您可以像这样创建自定义路由约束:
public class MaxIntConstraint : IRouteConstraint
{
public bool Match (HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
// just use int.TryParse because if it can't fit it won't parse
int val;
return int.TryParse(values[parameterName].ToString(), out val);
}
}
Run Code Online (Sandbox Code Playgroud)
你的路线看起来像这样:
routes.MapRoute(
name: "Default", // Route name
url: "{controller}/{action}/{id}", // URL with parameters
defaults: new { controller = "Application", action = "Index", id = 0 }, // Parameter defaults
constraints: new { id = new MaxIntConstraint() }
);
Run Code Online (Sandbox Code Playgroud)
当然,约束是非常具体的,可以通过更多的错误检查来修饰,但你明白了。