我正在尝试使用以下格式为 URL 创建自定义路由:
http://domain/nodes/{item_1}/{item_2}/{item3_}/..../{item_[n]}
基本上,可能存在随机量的 item_[n],例如
http://domain/nodes/1/3/2
http://domain/nodes/1
http://domain/nodes/1/25/11/45
使用我的自定义路由,我想检索一个项目数组并用它们做一些逻辑(验证并添加一些特定信息以请求上下文)。
例如,从 [http://domain/nodes/1/25/11/45] 中,我想获取一个 [1, 25, 11, 45] 的数组并对其进行处理。
所以,我这里有 2 个问题。
第一个实际上是一个问题。我看对了方向吗?或者可能有一种更简单的方法来实现这一点(也许没有自定义路由)?
第二个问题是将传入 url 与正则表达式模式匹配。有人可以帮我吗?
提前致谢:)
为了解决您的问题,我认为一种方法可能是创建一个路由类,然后处理参数。
public class CustomRouting : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
var repository = new FakeRouteDB(); //Use you preferred DI injector
string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath;
string[] sections = requestUrl.Split('/');
/*
from here you work on the array you just created
you can check every single part
*/
if (sections.Count() == 2 && sections[1] == "")
return null; // ~/
if (sections.Count() > 2) //2 is just an example
{
result = new RouteData(this, new MvcRouteHandler());
result.Values.Add("controller", "Products");
result.Values.Add("action", "Edit");
result.Values.Add("itmes0", sections[1]);
if (sections.Count() >= 3)
result.Values.Add("item2", sections[2]);
//....
}
else
{
//I can prepare a default route
result = new RouteData(this, new MvcRouteHandler());
result.Values.Add("controller", "Home");
result.Values.Add("action", "Index");
}
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
//I just work with outbound so it's ok here to do nothing
return null;
}
}
在全球.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new CustomRouting());
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
这应该让你了解我的想法。希望对你有帮助
我无法帮助您解决问题的第一部分,但我可以尝试创建正则表达式。
在您的示例中,所有项目都是数字 - 这是唯一的选择吗?如果没有,请提供有关可能字符的更多信息。
目前,正则表达式将是:
@"http://domain/nodes(?:/(d+))*"
(?:)
是非捕获组,()
是捕获组。
如果匹配所有匹配事件,则最终将得到组1-n
,其中每个组将包含匹配的数字(组编号 0 将是整个匹配项)。