MVC 默认路由不适用于控制器

MVC Default Route not Working for Controller

我刚刚开始一个新的 MVC 项目,默认路由似乎没有像我预期的那样工作。

路由配置:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

我有一个 ActionLink 去 "Scripts" 控制器上的 "Index" 动作 @Html.ActionLink("Scripts", "Index", "Scripts")

public class ScriptsController : Controller
{
    public ActionResult Index()
    {
        var model = new IndexModel();
        .......
        return View(model);
    }
}

单击此 link 时,浏览器会尝试导航到“http://localhost:1733/Scripts/", and the browser displays a "Directory listing denied" error. When I manually change the URL to "http://localhost:1733/Scripts/Index”,它工作正常。

默认路由不应该自动推断 "Index" 操作吗? 它似乎确实适用于作为默认 MVC 站点模板一部分的 ManageController class(“http://localhost:1733/Manage” 显示 [=14= 的 Index ActionResult ])

我做错了什么?

我猜你的应用程序根目录中有一个物理“Scripts”。您看到的错误消息是预期的行为。当 /Scripts 的 GET 请求到来时,IIS 不知道是 return 目录内容(脚本)还是 mvc return ScriptsController 结果。令人困惑。

您应该尽量不要将您的控制器命名为与物理目录名称相同的名称。更改其中一个名称。

如果您不想重命名其中任何一个,您可以将 RouteExistingFiles 属性 设置为 true 以告知框架路由是否应处理与现有物理匹配的 url file/directory.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute("Default", "{controller}/{action}/{id}",
             new { controller = "Home", action = "Index", id = UrlParameter.Optional });

        routes.RouteExistingFiles = true;
    }
}

您需要确保 ScriptsController 中没有任何与物理 files/static 资源匹配的操作方法(例如:bundled/minimized 脚本资源名称)。