有没有可能让url带有自定义的文字分隔符,可以有默认的参数?
context.MapRoute(
"Forums_links",
"Forum/{forumId}-{name}",
new { area = "Forums", action = "Index", controller = "Forum" },
new[] { "Jami.Web.Areas.Forums.Controllers" }
);正如你所看到的,我使用破折号将id与名称分开,这样我就可以拥有像这样的url:
/Forum/1-forum-name而不是:
/Forum/1/forum-name我发现问题是我使用了多个破折号。和路由引擎不知道该分离哪一个。但总的来说,这并没有改变我的问题,因为我无论如何都想使用多个破折号。
发布于 2011-07-02 03:26:15
非常有趣的问题。
我能想到的唯一方法很像Daniel的,只有一个额外的功能。
context.MapRoute(
"Forums_links",
"Forum/{forumIdAndName}",
new { area = "Forums", action = "Index", controller = "Forum" },
new { item = @"^\d+-(([a-zA-Z0-9]+)-)*([a-zA-Z0-9]+)$" } //constraint
new[] { "Jami.Web.Areas.Forums.Controllers" }
);这样,将与此路由匹配的唯一项目是格式为以下模式的项目:
[one or more digit]-[zero or more repeating groups of string separated by dashes]-[final string]在这里,您将使用Daniel posted的方法来解析forumIdAndName参数中所需的数据。
发布于 2011-07-01 20:36:11
实现这一点的一种方法是将id和name组合到同一路由值中:
context.MapRoute(
"Forums_links",
"Forum/{forumIdAndName}",
new { area = "Forums", action = "Index", controller = "Forum" },
new[] { "Jami.Web.Areas.Forums.Controllers" }
);然后从中提取Id:
private static int? GetForumId(string forumIdAndName)
{
int i = forumIdAndName.IndexOf("-");
if (i < 1) return null;
string s = forumIdAndName.Substring(0, i);
int id;
if (!int.TryParse(s, out id)) return null;
return id;
}https://stackoverflow.com/questions/6546655
复制相似问题