要在ASP.NET Core 3.1 MVC应用程序中的子目录中搜索视图,可以使用自定义视图位置解析器。
以下是一个解决方法的示例:
using Microsoft.AspNetCore.Mvc.Razor;
using System.Collections.Generic;
namespace YourNamespace
{
public class SubdirectoryViewLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
// 不需要实现
}
public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations)
{
// 获取当前控制器和视图的文件夹路径
string controllerName = context.Values["controller"] as string;
string viewName = context.Values["action"] as string;
// 指定子目录的名称
string subdirectoryName = "Subdirectory"; // 替换为你的子目录名称
// 构建新的视图位置
foreach (var location in viewLocations)
{
yield return location.Replace("{0}", subdirectoryName + "/{0}"); // 替换视图名称中的占位符
yield return location.Replace("{1}", subdirectoryName + "/{1}"); // 替换控制器名称中的占位符
}
}
}
}
在Startup.cs文件的ConfigureServices方法中,添加以下代码:
services.Configure(options =>
{
options.ViewLocationExpanders.Add(new SubdirectoryViewLocationExpander());
});
例如,如果你有一个名为HomeController的控制器,你可以创建一个Subdirectory/Home文件夹,并在其中创建一个Index.cshtml的视图文件。
这样,ASP.NET Core MVC将会在子目录中搜索视图。
希望以上解决方法对你有所帮助!