ASP.NET MVC:路线与可选参数,但如果提供,必须匹配\\ D + [英] ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+
问题描述
我试着写在它可为空int类型的路线。应该可以去这两个 /型材/
也 /型材/ \\ D +
。
I'm trying to write a route with a nullable int in it. It should be possible to go to both /profile/
but also /profile/\d+
.
routes.MapRoute("ProfileDetails", "profile/{userId}",
new {controller = "Profile",
action = "Details",
userId = UrlParameter.Optional},
new {userId = @"\d+"});
正如你所看到的,我说,用户id
是可选的,但也是它应该匹配正前pression \\ D +
。这不工作,我知道为什么了。
As you can see, I say that userId
is optional but also that it should match the regular expression \d+
. This does not work and I see why.
不过,我将如何构建一个仅匹配 /型材/
也 /型材/
后跟一个路由号码是多少?
But how would I construct a route that matches just /profile/
but also /profile/
followed by a number?
推荐答案
的简单的方法是只需添加另一条路线,而不用户id
参数,让你有一个备用的:
The simplest way would be to just add another route without the userId
parameter, so you have a fallback:
routes.MapRoute("ProfileDetails", "profile/{userId}",
new {controller = "Profile",
action = "Details",
userId = UrlParameter.Optional},
new {userId = @"\d+"});
routes.MapRoute("Profile", "profile",
new {controller = "Profile",
action = "Details"});
据我所知,你能做到这一点的唯一的其他方式将是一个自定义的约束。所以,你的路线将变成:
As far as I know, the only other way you can do this would be with a custom constraint. So your route would become:
routes.MapRoute("ProfileDetails", "profile/{userId}",
new {controller = "Profile",
action = "Details",
userId = UrlParameter.Optional},
new {userId = new NullableConstraint());
和自定义约束code将是这样的:
And the custom constraint code will look like this:
using System;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
namespace YourNamespace
{
public class NullableConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest && parameterName == "userId")
{
// If the userId param is empty (weird way of checking, I know)
if (values["userId"] == UrlParameter.Optional)
return true;
// If the userId param is an int
int id;
if (Int32.TryParse(values["userId"].ToString(), out id))
return true;
}
return false;
}
}
}
我不知道 NullableConstraint
是最好的名字在这里,但是这是给你的!
I don't know that NullableConstraint
is the best name here, but that's up to you!
这篇关于ASP.NET MVC:路线与可选参数,但如果提供,必须匹配\\ D +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!