3 c# asp.net-mvc asp.net-mvc-routing asp.net-mvc-3
我有以下路线:
context.MapRoute(
"content",
"{page}/{title}",
new { controller = "Server", action = "Index" },
new { page = @"^[AFL][0-9A-Z]{4}$" }
);
Run Code Online (Sandbox Code Playgroud)
此路由用于以下页面:
/A1234
/F6789
/L0123
Run Code Online (Sandbox Code Playgroud)
然而它也抓住了:/Admin这是我不想要的东西.
我提出了一个临时解决方案,看起来像这样:
context.MapRoute(
"content",
"{page}/{title}",
new { controller = "Server", action = "Index" },
new { page = @"^[AFL][0-9][0-9A-Z]{3}$" }
);
Run Code Online (Sandbox Code Playgroud)
这只能起作用,因为现在我的所有页面的第二个数字都是0.
有没有办法我可以配置我的路由接受A,F或L后跟4个大写字符,但它没有捕获"dmin"?
不确定是否是这种情况,但我认为正则表达式不应该接受"dmin",因为它是小写的,我只指定AZ.但是当用作MVC路由时,它确实需要"dmin".有没有人知道ASP MVC内部是否将其转换为全部大写?
默认路由处理在匹配URL时忽略大小写(请参阅下面的代码),这也是您案例中Admin的匹配原因.您应该做的就是编写一个自定义路由约束类,它实现IRouteConstraint接口和实现Match方法,以区分大小写.
Route类如果你看看默认Route类如何处理约束,这就是代码:
protected virtual bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
IRouteConstraint routeConstraint = constraint as IRouteConstraint;
// checks custom constraint class instances
if (routeConstraint != null)
{
return routeConstraint.Match(httpContext, this, parameterName, values, routeDirection);
}
// No? Ok constraint provided as regular expression string then?
string text = constraint as string;
if (text == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("Route_ValidationMustBeStringOrCustomConstraint"), new object[]
{
parameterName,
this.Url
}));
}
object value;
values.TryGetValue(parameterName, out value);
string input = Convert.ToString(value, CultureInfo.InvariantCulture);
string pattern = "^(" + text + ")$";
// LOOK AT THIS LINE
return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);
}
Run Code Online (Sandbox Code Playgroud)
最后一行实际匹配提供的正则表达式路由约束.你可以看到它忽略了大小写.因此,第二个可能的解决方案是写一个新的Route,从这个默认的继承类Route类和重写ProcessConstraint方法不忽略大小写.其他一切都可以保持不变.
| 归档时间: |
|
| 查看次数: |
1405 次 |
| 最近记录: |