[英]Infinite URL Parameters for ASP.NET MVC Route
我需要一個可以在我的 ASP.NET 控制器上獲得無限參數的實現。 如果我給你一個例子會更好:
讓我們假設我將有以下網址:
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;
}
有沒有已知的方法來實現這一目標? 如何從控制器獲取值? 使用Dictionary<string, string>
或List<string>
?
筆記 :
這個問題沒有很好地解釋 IMO,但我盡力適應它。 in. 隨意調整它
像這樣:
routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... });
ActionResult MyAction(string tags) {
foreach(string tag in tags.Split("/")) {
...
}
}
catch all 會給你原始字符串。 如果您想要一種更優雅的方式來處理數據,您始終可以使用自定義路由處理程序。
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();
}
這就是所謂的包羅萬象:
tag/{*tags}
萬一有人要來此與MVC在.NET 4.0中,你需要一個定義你的路由要小心。 我很高興去global.asax
並按照這些答案(和其他教程)中的建議添加路由,但一無所獲。 我的路由都默認為{controller}/{action}/{id}
。 向 URL 添加更多段給了我 404 錯誤。 然后我在 App_Start 文件夾中發現了 RouteConfig.cs 文件。 原來這個文件是由global.asax
在Application_Start()
方法中調用的。 因此,在 .NET 4.0 中,請確保在那里添加自定義路由。 這篇文章很好地介紹了它。
例如,在 asp .net core 中,您可以在路由中使用 *
[HTTPGet({*id})]
此代碼可以多參數或使用帶斜杠的發送字符串時使用它們來獲取所有參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.