ASP.NET MVC路由的无限URL参数
我需要一个可以在ASP.NET控制器上获取无限参数的实现。如果我给你举个例子会更好: 假设我将有以下URL:ASP.NET MVC路由的无限URL参数,asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-routing,Asp.net,Asp.net Mvc,Asp.net Mvc 3,Asp.net Mvc Routing,我需要一个可以在ASP.NET控制器上获取无限参数的实现。如果我给你举个例子会更好: 假设我将有以下URL: example.com/tag/poo/bar/poobar example.com/tag/poo/bar/poobar/poo2/poo4 example.com/tag/poo/bar/poobar/poo89 正如您所看到的,它将在example.com/tag/之后获得无限多的标记,斜杠将在这里作为分隔符 在控制器上,我要执行以下操作: foreach(string item
example.com/tag/poo/bar/poobar
example.com/tag/poo/bar/poobar/poo2/poo4
example.com/tag/poo/bar/poobar/poo89
正如您所看到的,它将在example.com/tag/
之后获得无限多的标记,斜杠将在这里作为分隔符
在控制器上,我要执行以下操作:
foreach(string item in paramaters) {
//this is one of the url paramaters
string poo = item;
}
有没有已知的方法来实现这一点?我如何从控制器获取和达到值?使用字典
或列表
注意:
这个问题在国际海事组织解释得不好,但我尽了最大努力去解决它。
在里面请随意调整
像这样:
routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... });
ActionResult MyAction(string tags) {
foreach(string tag in tags.Split("/")) {
...
}
}
这叫做:
一网打尽会给你一根粗线。如果希望以更优雅的方式处理数据,可以始终使用自定义路由处理程序
public class AllPathRouteHandler : MvcRouteHandler
{
private readonly string key;
public AllPathRouteHandler(string key)
{
this.key = key;
}
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var allPaths = requestContext.RouteData.Values[key] as string;
if (!string.IsNullOrEmpty(allPaths))
{
requestContext.RouteData.Values[key] = allPaths.Split('/');
}
return base.GetHttpHandler(requestContext);
}
}
routes.Add(new Route("tag/{*tags}",
new RouteValueDictionary(
new
{
controller = "Tag",
action = "Index",
}),
new AllPathRouteHandler("tags")));
注册路由处理程序
public class AllPathRouteHandler : MvcRouteHandler
{
private readonly string key;
public AllPathRouteHandler(string key)
{
this.key = key;
}
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var allPaths = requestContext.RouteData.Values[key] as string;
if (!string.IsNullOrEmpty(allPaths))
{
requestContext.RouteData.Values[key] = allPaths.Split('/');
}
return base.GetHttpHandler(requestContext);
}
}
routes.Add(new Route("tag/{*tags}",
new RouteValueDictionary(
new
{
controller = "Tag",
action = "Index",
}),
new AllPathRouteHandler("tags")));
在控制器中以数组形式获取标记
public ActionResult Index(string[] tags)
{
// do something with tags
return View();
}
万一有人用.NET4.0中的MVC来解决这个问题,你需要小心定义路线的地方。我很高兴地去了
global.asax
,并按照这些答案(以及其他教程)中的建议添加了路线,结果一无所获。我的所有路由都默认为{controller}/{action}/{id}
。在URL中添加更多的段给了我一个404错误。然后我在App_Start文件夹中发现了RouteConfig.cs文件。原来这个文件是由Application\u Start()
方法中的global.asax
调用的。因此,在.NET4.0中,请确保在那里添加自定义路由。漂亮地覆盖了它。在asp.net核心中,您可以在路由中使用*
比如说
[HTTPGet({*id})]
这段代码可以是多参数的,或者在使用带斜杠的send字符串时使用它们来获取所有参数,看起来非常整洁。我来试试,{*tags}的作用是什么?特别是,*。这是一个包罗万象的参数。那么,我们可以像那样在ASP.NET MVC框架上使用所有通配符参数,还是只使用*?@tugberk:您只能使用*,并且它必须始终是catch all参数的第一个字符。它不是任何形式的通配符。这只是意味着这个路由参数将捕获URL中从该点开始的所有内容。这并没有提供问题的答案。一旦你有足够的钱,你将能够;相反@伊内杜姆:为什么不呢?