传统的路由默认值意味着我们能够访问这些 URL 并且总是以相同的操作结束:
/
/Home
/Home/Index
但是今天我们会在这些行中写一些东西:
[RoutePrefix("Home")]
[Route("{action=Index}")]
public class HomeController
{
public ActionResult Index() {}
public ActionResult ...
}
但是这个路由定义绝不相同。
/ (fails)
/Home (works)
/Home/Index (works)
因此,如果我们将上面的代码更改为
[RoutePrefix("Home")]
[Route("{action=Index}")]
public class HomeController
{
[Route("~/")]
public ActionResult Index() {}
public ActionResult ...
}
但随后我们将处理颠倒过来:
/ (works)
/Home (fails)
/Home/Index (fails)
我们可以通过以下方式使声明性代码更加冗长,并使其像老式路由机制一样工作:
[RoutePrefix("Home")]
[Route("{action=Index}")]
public class HomeController
{
[Route("~/")]
[Route("~/Home")]
[Route("~/Home/Index")]
public ActionResult Index() {}
public ActionResult ...
}
这适用于所有三种不同的路线。
问题
这个问题当然与默认控制器和操作的应用程序默认操作有关。只是我想知道这是否是唯一的方法?有没有更简洁的代码方式让它按预期工作?