正如标题所述,我希望我的MVC网站有一个像
这样的网址模式/Products/Category/Books/Sku/123456
其他每个url段都是参数名称及其值的/ name / value。
我该怎么做?
答案 0 :(得分:10)
ASP.NET路由允许在路由掩码的末尾定义 catchall 参数:
routes.MapRoute(
"CategoryWithParameters",
"Products/Category/{category}/{*parameters}",
new { controller = "Home", action = "Index" }
);
所以这个家庭控制器方法
public ActionResult Index(string category, string parameters)
{
// slashes were ignored by routing system
string[] parts = parameters.Split('/');
Dictionary<string, string> values = new Dictionary<string, string>();
// we want only keys with values
for (int i = 0; i < parts.Length / 2 * 2; i += 2)
values[parts[i]] = parts[i + 1];
ViewBag.category = category;
ViewBag.parameters = parameters;
ViewBag.values = values;
return View();
}
和这个观点
<p>
@ObjectInfo.Print(ViewBag.category)
</p>
<p>
@ObjectInfo.Print(ViewBag.parameters)
</p>
<p>
@ObjectInfo.Print(ViewBag.values)
</p>
渲染网址h ** p:// localhost:32690 / Products / Category / Books / Sku / 123456 / Bro / 098765 / df / 34 to