MVC Handler用于未知数量的可选参数

Eri*_*ham 3 asp.net-mvc url-routing actionresult asp.net-mvc-routing

我正在使用MVC路由,它将在URL的末尾获取未知数量的参数.像这样的东西:

domain.com/category/keyword1/keyword2/.../keywordN

这些关键字是我们必须匹配的过滤器的值.

到目前为止,我能想到的唯一方法是UGLY ......只需创建一个ActionResult,其参数多于我可能需要的参数:

ActionResult CategoryPage(string urlValue1,string urlValue2,string urlValue3等...){}

这感觉不对劲.我想我可以将它们塞进一个查询字符串中,但后来我丢失了性感的MVC URL,对吧?有没有更好的方法来声明处理程序方法,以便它处理未知数量的可选参数?

必须在Application Start上连接路由,这应该不是那么难.关键字的最大数量可以很容易地从数据库中确定,因此没有大问题.

谢谢!

Kri*_*aes 6

你可以使用像这样的catch-all参数:

routes.MapRoute("Category", "category/{*keywords}", new { controller = "Category", action = "Search", keywords = "" });
Run Code Online (Sandbox Code Playgroud)

然后,您的搜索操作方法中将有一个参数:

public ActionResult Search(string keywords)
{
    // Now you have to split the keywords parameter with '/' as delimiter.
}
Run Code Online (Sandbox Code Playgroud)

以下是可能的URL列表,其中包含keywords参数的值:

http://www.example.com/category(关键字: "")
http://www.example.com/category/foo(关键词: "富")
http://www.example.com/category/foo/bar(关键字:"foo/bar")
http://www.example.com/category/foo/bar/zap(keywords:"foo/bar/zap")