在 asp.net core mvc 中,我为视图指定了多个位置。因此,如果某个位置缺少视图,则会从另一个位置获取视图。
我有一个带有 asp.net core mvc 的 CMS,其中控制器和视图位于已编译的库中。如果我不想使用库中的视图,很容易添加一个新视图,例如/Views/ControllerName/Index.cshtml
,然后应用程序将使用此视图而不是从库中获取。
如何在剃须刀页面中完成?基本上,我希望通过在某个位置添加 .cshtml 文件来覆盖任何页面的剃刀视图。
在 asp.net core mvc 中,我为视图指定了多个位置。因此,如果某个位置缺少视图,则会从另一个位置获取视图。
我有一个带有 asp.net core mvc 的 CMS,其中控制器和视图位于已编译的库中。如果我不想使用库中的视图,很容易添加一个新视图,例如/Views/ControllerName/Index.cshtml
,然后应用程序将使用此视图而不是从库中获取。
如何在剃须刀页面中完成?基本上,我希望通过在某个位置添加 .cshtml 文件来覆盖任何页面的剃刀视图。
使用IViewLocationExpander
, 在默认位置之前添加您的自定义位置。
这是一个查看“覆盖”文件夹的示例:
public class MyViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(
ViewLocationExpanderContext context,
IEnumerable<string> viewLocations)
{
// {2} = Area
// {1} = Controller
// {0} = Action
var locations = new string[] { "/Views/Override/{2}/{1}/{0}.cshtml" };
return locations.Union(viewLocations);
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
}
然后在你的Startup
班级注册它:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new MyViewLocationExpander());
});
}
使用此处建议的其他解决方案(IViewLocationExpander 或 PageViewLocationFormats),我没有让它在 ASP.NET Core 2.2 中工作。对我有用的是结合使用 PageRouteModelConvention 和 ActionConstraint。
这是一个用于本地化的类似解决方案: