ASP.NET MVC:带有可选参数的路由,但如果提供,则必须匹配 d+ [英] ASP.NET MVC: Route with optional parameter, but if supplied, must match d+
问题描述
我正在尝试编写一个包含可为空 int 的路由.应该可以同时访问 /profile/
和 /profile/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+"});
如您所见,我说 userId
是可选的,但它也应该匹配正则表达式 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.
但是我如何构建一个既匹配 /profile/
又匹配 /profile/
后跟一个数字的路由?
But how would I construct a route that matches just /profile/
but also /profile/
followed by a number?
推荐答案
最简单的 方法是添加另一个没有 userId
参数的路由,这样你就有了回退:
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());
自定义约束代码将如下所示:
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屋!