[英]How to specify custom location (absolute path) to load areas in asp.net core mvc?
我正在尝试通过指定绝对路径 (C:/WebApplication7/MS/{2}/Views/{1}/{0}.cshtml)从自定义目录加载区域。 我尝试在Startup.cs中指定AreaLocationFormats并实现IViewLocationExpander 。 当我提供相对路径 (/MS/{2}/Views/{1}/{0}.cshtml)时,这两个都可以正常工作,但我需要通过提供目录的确切路径来加载视图,因为我的视图将存在于单独的目录中。 这在某种程度上可能吗?
services.AddControllersWithViews()
.AddRazorOptions(options =>
{
options.AreaViewLocationFormats.Add(@"/MS/{2}/Views/{1}/{0}.cshtml");
});
services.AddControllersWithViews()
.AddRazorOptions(options =>
{
options.ViewLocationExpanders.Add(new ViewLocationExpander());
});
public class ViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
//{2} is area, {1} is controller,{0} is the action
string[] locations = new string[] { "/MS/{2}/Views/{1}/{0}.cshtml" };
return locations.Union(viewLocations); //Add mvc default locations after ours
}
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values["customviewlocation"] = nameof(ViewLocationExpander);
}
}
如果要指定区域内查看的具体路径,可以在app.UseEndpoints
中设置。
假设我的区域名称是MyArea
。
在 startup.cs 的Configure
方法中:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyArea",
pattern: "C:/WebApplication7/MS/{area:exists}/Views/{controller=Home}/{action=Index}.cshtml");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapBlazorHub();
});
通过更多的研究,我能够通过配置一个新的FileProvider来做到这一点
安装Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation nuget package 和 Startup.cs 中的行
services.Configure<MvcRazorRuntimeCompilationOptions>(options => {
options.FileProviders.Add(new PhysicalFileProvider(@"C:/WebApplication7"));
});
有关配置文件提供程序的详细信息: https://github.com/dotnet/AspNetCore.Docs/issues/14593
使用 FileProvider 定义上述两种方法都可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.