ASP.NET MVC 5:单个控制器的方法来处理文件浏览器模式的路径 [英] ASP.NET MVC 5: single controller method to handle paths in file browser mode
问题描述
我想有一些控制器与一个方法,可以让我通过一些层次结构(文件系统等)进行导航。
I want to have some controller with the single method that would allow me to navigate through some hierarchy (file system etc.).
在换句话说,我想有可能访问此方法具有灵活的路线,并得到路由作为参数的一部分。例如,在这个层次结构的情况下
In other words I want to have possibility to access this method with flexible routes and get part of routes as parameter. For example in case of this hierarchy
Root
Sub-folder-A
Sub-folder-B
Sub-folder-C
我希望有下一个途径访问文件夹
I want to have access folders with the next routes
mymvcapplication/explorer/root
mymvcapplication/explorer/root/sub-folder-a
mymvcapplication/explorer/root/sub-folder-b/sub-folder-c
什么,我应该在哪里配置正确地实现它?
What and where should I configure to implement it properly?
推荐答案
要支持可变数量在请求URL URL参数值,你可以标记与你的方法参数*
preFIX在路由定义。
To support variable number of url parameter values in the request url, you can mark your method parameter with *
prefix in the route definition.
使用MVC属性的路由,
With MVC Attribute routing,
[Route("explorer/root/{*levels}")]
public ActionResult Details(string levels = "")
{
if (String.IsNullOrEmpty(levels))
{
//request for root
}
else
{
var levelArray = levels.Split('/');
//check level array and decide what to do
}
return Content("Make sure to return something valid :) ");
}
与pfixed最后一个参数$ P $ *
就像 包罗万象的参数将存储任何东西在探险家/根后,网址
所以,当你要求 yoursite.com/explorer/root/a/b/c/d
,默认的模型绑定将映射值 A / b / C / D
到级别
参数。您可以拨打该字符串的拆分
方法来获取URL段的数组。
So when you request yoursite.com/explorer/root/a/b/c/d
, the default model binder will map the value "a/b/c/d"
to the levels
parameter. You can call the Split
method on that string to get an array of url segments.
要启用属性的路由,转到 RouteConfig.cs
并调用 MapMvcAttributeRoutes()
方法在的RegisterRoutes
。
To enable attribute routing, go to RouteConfig.cs
and call the MapMvcAttributeRoutes()
method in the RegisterRoutes
.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
这篇关于ASP.NET MVC 5:单个控制器的方法来处理文件浏览器模式的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!