You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC如何配置路由模板,使默认动作映射到带控制器名的视图?

实现自定义默认视图映射(适配屏幕阅读器需求)

完全可行,你可以通过修改视图查找逻辑来实现这个需求,具体方案如下:

  • 自定义视图查找规则(推荐)
    无需修改路由,只需要调整视图引擎的查找优先级,让系统优先匹配{ControllerName}Index.cshtml文件:

    • 针对ASP.NET Core MVC,在Program.cs中添加视图位置规则:
      builder.Services.AddControllersWithViews()
          .AddRazorOptions(options =>
          {
              // 将自定义视图路径放在最前面,提升优先级
              options.ViewLocationFormats.Insert(0, "~/Views/{1}/{1}Index.cshtml");
              options.ViewLocationFormats.Insert(1, "~/Views/Shared/{1}Index.cshtml");
          });
      
    • 针对ASP.NET MVC 5及更早版本,创建自定义视图引擎并注册:
      public class CustomViewEngine : RazorViewEngine
      {
          public CustomViewEngine()
          {
              ViewLocationFormats = new[]
              {
                  "~/Views/{1}/{1}Index.cshtml",
                  "~/Views/{1}/Index.cshtml",
                  "~/Views/Shared/{1}Index.cshtml",
                  "~/Views/Shared/Index.cshtml"
              };
          }
      }
      
      在Global.asax.cs的Application_Start方法中注册:
      protected void Application_Start()
      {
          ViewEngines.Engines.Clear();
          ViewEngines.Engines.Add(new CustomViewEngine());
          // 其他初始化代码
      }
      

    配置后,访问/home这类默认路由时,系统会优先加载HomeIndex.cshtml,屏幕阅读器编辑文件时会播报完整文件名,直接关联到所属控制器。

  • 修改默认路由动作(可选)
    如果希望控制器的默认动作也对应{ControllerName}Index,可以调整路由模板的默认动作值:

    • ASP.NET Core MVC:
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=HomeIndex}/{id?}"
      );
      
    • ASP.NET MVC 5:
      routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "HomeIndex", id = UrlParameter.Optional }
      );
      

    这种方式需要将所有控制器的默认动作命名为{ControllerName}Index,灵活性不如修改视图查找规则。

内容的提问来源于stack exchange,提问作者PermanentNovice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 11:42:03