c# - 如何指定自定义位置(绝对路径)以在 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);
}
}
解决方案
通过更多的研究,我能够通过配置一个新的FileProvider来做到这一点
安装Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation nuget 包和 Startup.cs 中的行
services.Configure<MvcRazorRuntimeCompilationOptions>(options => {
options.FileProviders.Add(new PhysicalFileProvider(@"C:/WebApplication7"));
});
有关配置文件提供程序的详细信息:https ://github.com/dotnet/AspNetCore.Docs/issues/14593
使用 FileProvider 定义上述两种方法都可以正常工作。
推荐阅读
- java - 是否有与 jdbc 或其他数据库交互的类(类似于 contentProvider)?
- regex - python 正则表达式从论文的doi中删除多余的字符
- angular - 使用“forRoot”将配置数据传递给角度库的依赖项
- php - 如何在 Laravel 中将带有访问器的属性正确设置到模型中?
- javascript - material-ui输入选择属性隐藏body溢出-y滚动-react js
- apache - 当url包含特殊字符时如何重定向错误页面?
- python - 连接具有不同索引的数据帧
- angularjs - 如何在 Angular 指令中隐藏要在 DOM 中看到的属性?
- javascript - 如何重复执行一个命令并在抛出错误时执行另一个命令而不总是检查 if 条件?
- python - 用于老挝语分词和 PoS 标记的 LSTM Keras 实现