.net Core - 使用 Route 属性时未加载默认控制器

.net Core - Default controller is not loading when Route attribute is used

一个新的 .net 核心 Web 应用程序项目带有以下路由配置:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

如果您将其替换为 app.UseMvc() 并为 HomeController 及其操作(索引、关于、联系、错误)添加适当的 Route 属性,它仍然可以工作。由于我们没有指定默认路由,因此如果您点击 http://localhost:25137/,将不会呈现默认视图 (Home/Index)。希望理解正确!

现在,因为我需要在点击 http://localhost:25137/ 时显示默认视图,所以我将路由代码更改为 app.UseMvcWithDefaultRoute();,根据定义,它的作用相当于初始代码段。即使那样,它也没有渲染默认视图;但在使用完整的 URL(http://localhost:25137/home/index) 时有效。这意味着路由仍然有效,但不是默认路由!

然后我回到控制器并从 HomeController 及其操作中删除所有 Route 属性。然后默认路由没有任何问题。

这是预期的行为吗? 这种行为背后的原因可能是什么?

来自asp docs

Actions are either conventionally routed or attribute routed. Placing a route on the controller or the action makes it attribute routed. Actions that define attribute routes cannot be reached through the conventional routes and vice-versa. Any route attribute on the controller makes all actions in the controller attribute routed.

所以基本上,如果您使用属性,那么 UseMvcUseMvcWithDefaultRoute 中定义的路由将被忽略。在这种情况下只会使用该属性。

如果您想获得与带有可选段的默认路由类似的效果,您仍然可以使用多个路由属性。同样来自 asp docs 中的同一篇文章:

public class MyDemoController : Controller
{
   [Route("")]
   [Route("Home")]
   [Route("Home/Index")]
   public IActionResult MyIndex()
   {
      return View("Index");
   }
   [Route("Home/About")]
   public IActionResult MyAbout()
   {
      return View("About");
   }
   [Route("Home/Contact")]
   public IActionResult MyContact()
   {
      return View("Contact");
   }
}