ASP.Net MVC路由与RouteConstraint不起作用
问题描述:
正当我想我已经找到了路由,它不工作的方式,我认为它应该。我正在使用ASP.Net MVC 4 RC。这里是我的RouteConfig:ASP.Net MVC路由与RouteConstraint不起作用
routes.MapRoute
(
"TwoIntegers",
"{controller}/{action}/{id1}/{id2}",
new { controller = "Gallery", action = "Index", id1 = new Int32Constraint(), id2 = new Int32Constraint() }
);
routes.MapRoute
(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
这里是我的路由约束:
public class Int32Constraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values.ContainsKey(parameterName))
{
int intValue;
return int.TryParse(values[parameterName].ToString(), out intValue) && (intValue != int.MinValue) && (intValue != int.MaxValue);
}
return false;
}
}
/{domain.com}/PageSection/Edit/21
是越来越停在 “TwoIntegers” 路线。很明显,没有第二个整数被传递。
这里是我的错误:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'SolutiaConsulting.Web.ContentManager.Controllers.PageSectionController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
我在做什么错?我首先列出了更具体的路线。请帮忙。
答
您的约束没有正确指定。请确保您使用的是MapRoute
扩展方法的正确超载:
routes.MapRoute(
"TwoIntegers",
"{controller}/{action}/{id1}/{id2}",
new { controller = "Gallery", action = "Index" },
new { id1 = new Int32Constraint(), id2 = new Int32Constraint() }
);
注意,用于指定的约束,而不是3日第四个参数。
顺便说一句,你可以让你的代码更易读使用命名参数:
routes.MapRoute(
name: "TwoIntegers",
url: "{controller}/{action}/{id1}/{id2}",
defaults: new { controller = "Gallery", action = "Index" },
constraints: new { id1 = new Int32Constraint(), id2 = new Int32Constraint() }
);
而且怎么样一个正则表达式?
routes.MapRoute(
name: "TwoIntegers",
url: "{controller}/{action}/{id1}/{id2}",
defaults: new { controller = "Gallery", action = "Index" },
constraints: new { id1 = @"\d+", id2 = @"\d+" }
);
不会正则表达式的解决方案有溢出整数值的问题吗?例如如果用户输入大于Int32.MaxValue的id1或id2的值,它会中断吗? – StarCub 2013-12-18 03:31:01