asp.net-core - 覆盖 asp.net core razor 页面中的 razor View

标签 asp.net-core asp.net-core-mvc asp.net-core-2.0 razor-pages

在 asp.net core mvc 中,我为 View 指定了多个位置。因此,如果某个位置缺少 View ,则会从另一位置获取 View 。

我有一个带有 asp.net core mvc 的 CMS,其中 Controller 和 View 位于已编译的库中。如果我不想使用库中的 View ,很容易添加一个新 View ,例如/Views/ControllerName/Index.cshtml 然后应用程序将使用此 View 而不是从库中获取。

如何在 Razor 页面中完成此操作?基本上,我希望有一个选项可以通过在某个位置添加 .cshtml 文件来覆盖任何页面的 Razor View 。

最佳答案

使用 IViewLocationExpander,在默认位置之前添加自定义位置。

下面是一个查看“Override”文件夹的示例:

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());
    });
}

关于asp.net-core - 覆盖 asp.net core razor 页面中的 razor View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46230400/

相关文章:

asp.net-core - 为什么在 ASP.NET Core WebAPI 项目中使用 OAuth2 时会出现 'no authenticationScheme was specified' 错误?

c# - 为什么 Application Insights 依赖关系时间线存在间隙?

asp.net-web-api - ASP.net 5 中的 IApplicationBuilder.UseJwtBearerAuthentication 扩展在哪里?

c# - UWP 应用程序中的 HttpClient 缓存

c# - 自定义验证属性 : Comparing two properties in the same model

.net - 如何在域相关的 .NET Core 中更改/创建自定义 FileProvider(即一个 Web 应用程序为多个站点呈现逻辑提供服务)

c# - 用列表分离模型

vue.js - 使用 ASP.net Core 2.0 应用程序在 IIS 上托管时出现 VueJs Url 重写错误

visual-studio - 通过 Manage NuGet Packages 安装 Bootstrap 后,bootstrap 文件不显示以供引用

c# - 如何在 ASPNET.Core Web 应用程序中发送带有 CORS header 的 HTTP 4xx-5xx 响应?