如何制作适用于我所有控制器的路径“{controller} / {action} / paramname / paramvalue / ...”?

时间:2011-03-01 16:25:41

标签: asp.net-mvc-3 url-routing

正如标题所述,我希望我的MVC网站有一个像

这样的网址模式
/Products/Category/Books/Sku/123456

其他每个url段都是参数名称及其值的/ name / value。

我该怎么做?

1 个答案:

答案 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

rendered view