ASP.. NET MVC 5路由配置没有检查指定的文件夹

本文关键字:检查 文件夹 MVC NET 路由 配置 ASP | 更新日期: 2023-09-27 18:04:21

我在使用ASP路由引擎时遇到了一些麻烦,这些问题是不言自明的。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "GameGold",
        url: "Products/GameGold/{controller}/{action}/{id}",
        defaults: new { controller = "Coins", action = "Index", id = UrlParameter.Optional }
        );
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

当我进入URL localhost/Products/GameGold/Coins/时,会出现以下内容:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Coins/Index.aspx
~/Views/Coins/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Coins/Index.cshtml
~/Views/Coins/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

我的文件夹是这样布局的

/视图/产品/GameGold/硬币/Index.cshtml

ASP.. NET MVC 5路由配置没有检查指定的文件夹

您的" Index "视图未被找到的错误不是由路由定义引起的。

URL localhost/Products/GameGold/Coins/通过' GameGold '路由映射到CoinsController及其Index动作。

MVC的内置约定是在~/Views/[CONTROLLERNAME]文件夹中查找视图-因此它在~/Views/Coins/文件夹中查找。

要解决这个问题,您有两个选项:

1)。按照惯例,将/Views/Products/GameGold/Coins/Index.cshtml移动到/Views/Coins/Index.cshtml

2)。更改Razor引擎的ViewLocationFormats以适应您的目录布局。你可以在http://www.ryadel.com/en/asp-net-mvc-add-custom-locations-to-the-view-engine-default-search-patterns/等博客文章中找到详细信息这篇文章中的一个例子:

// Add /MyVeryOwn/ folder to the default location scheme for STANDARD Views
var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
razorEngine.ViewLocationFormats = 
    razorEngine.ViewLocationFormats.Concat(new string[] { 
        "~/Views/Products/GameGold/{1}/{0}.cshtml",
        "~/Views/Products/GameGold/{0}.cshtml"
        // add other folders here (if any)
    }).ToArray();