MVC:如何管理URL slahses诠释第一个路由参数 [英] MVC: How to manage slahses in URL int the first route parameter
问题描述
我需要映射可能包含斜线两个变量,一个控制器,在我的ASP MVC应用程序。让我们来看看一个例子。
I need to map two variables that could contain slashes, to a controller, in my ASP MVC application. Let's see this with an example.
- 信息库和路径将URL-CN codeD参数。
- 库可以有0斜线或1斜线作为最大(代表或代表/模块)
- 路径可以有斜线任意数量。
例如,这些都是有效的网址:
For example these are valid URLs:
http://mysite/rep/Items
http://mysite/rep/module/Items/foo/bar/file.c
有人可能会提供有关如何定义这条路一些建议吗?
Someone could give some suggestions about how to define this route?
推荐答案
最后,根据在达林季米特洛夫的答案一>,我实现了下面的自定义路径,即解决了我的问题:
Finally, based in the answer of Darin Dimitrov, I implemented the following custom route, that solves my problem:
public class RepositoryRoute : Route
{
public RepositoryRoute(string name, string url, object defaults)
: base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
{
string moduleUrl = url.Replace(
REPOSITORY_PARAMETER, REPOSITORY_PARAMETER + MODULE_PARAMETER);
mModuleRoute = new Route(
moduleUrl, new RouteValueDictionary(defaults), new MvcRouteHandler());
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData rd = mModuleRoute.GetRouteData(httpContext);
if (rd == null)
return base.GetRouteData(httpContext);
if (!rd.Values.ContainsKey(MODULE))
return rd;
// set repository as repo/submodule format
// if a submodule is present in the URL
string repository = string.Format("{0}/{1}",
rd.Values[REPOSITORY],
rd.Values[MODULE]);
rd.Values.Remove(MODULE);
rd.Values[REPOSITORY] = repository;
return rd;
}
Route mModuleRoute;
const string REPOSITORY = "repository";
const string MODULE = "module";
const string REPOSITORY_PARAMETER = "{" + REPOSITORY + "}/"; // {repository}/
const string MODULE_PARAMETER = "{" + MODULE + "}/"; // {module}/
}
其中被登记在以下方式:
Which is registered in the following way:
routes.Add(new RepositoryRoute(
"Items",
"{repository}/Items/{*path}",
new { controller = "Items", action = "Index", path = "/" }
));
该航线使用内部路由,它定义了一个模块参数,如果它的发现,我Concat的到资源库,并将其删除。因此,映射的信息库和资源库/模块是透明的。
The route uses an internal route, that defines a module parameter, and if it's found, I concat it to the repository, and remove it. So mapping repository or repository/module is transparent.
这篇关于MVC:如何管理URL slahses诠释第一个路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!