我创建了一个demo application for you here。
您将需要使用您的 appsettings.json 文件,并将您的设置注入您的视图中。
在我的appsettings.json 中,我添加了一个名为“ViewConfiguration”的部分:
"ViewConfiguration": {
"ExampleKey": "ExampleValue"
}
您的各种值需要进入您的 ViewConfiguration 部分。
例如,我有ExampleKey,您将使用像“IndexPageStyleSheet”这样的通用名称,而我有ExampleValue,您需要使用新的样式表路径更新每个版本。仅当文件名更改时才需要更新。
然后我创建了一个ViewConfiguration class,它存储了 appsettings.json 文件中的所有值。
您需要为每个配置行创建一个属性,并确保该属性的名称与您的 appsettings.json 中的键名称匹配。
例如,我的 appsettings.json 有 ExampleKey,我的 ViewConfiguration 类也有 ExampleKey。
public class ViewConfiguration {
public string ExampleKey { get; set; }
}
在您的 Startup.cs 中,您需要告诉您的 IOC 容器将您的配置值加载到您的配置对象中。
在my Startup.cs 中,我的ConfigureServices 方法会自动将我的“ExampleValue”加载到ViewConfiguration.ExampleKey 中。
public void ConfigureServices(IServiceCollection services) {
// This line is the magic that loads the values from appsettings.json into a ViewConfiguration object.
services.Configure<ViewConfiguration>(Configuration.GetSection("ViewConfiguration"));
services.AddMvc();
}
现在,在我的_ViewImports.cshtml 中,我注入了我的 ViewConfiguration 对象,这样我就不需要将它注入到每个页面中。这可以是_ViewImports.cshtml 文件中的任何位置。如果您只想为每个文件夹注入特定的配置,您可以为每个文件夹创建一个新的 _ViewImports.cshtml 文件,并将不同的配置对象注入每个文件夹。它很灵活。
@using Microsoft.Extensions.Options;
@* Please rename this variable to something more appropriate to your application: *@
@inject IOptions<ViewConfiguration> InjectedViewConfig
现在,在任何页面中,您都可以简单地引用 ViewConfiguration 对象中的属性。
例如在my Index.cshtml中,我通过引用InjectedViewConfig.Value上的强类型属性来引用ViewConfiguration.ExampleKey属性,并在页面上输出“ExampleValue”。
这个值可以像文件名一样容易地注入到脚本或 css 链接标签中。它非常灵活。
<h1>Value: @InjectedViewConfig.Value.ExampleKey</h1>
通过进一步研究,您将能够从任何配置源注入这些值,例如 Azure 应用程序设置或 Azure Key Vault。详情请见this article。