我想一次从 json 文件中加载所有设置键值对,并在需要时在 mvc 6 View 页面中使用设置键值。如果提供最佳解决方案,我将不胜感激。我有如下场景
if(Settings.enable_logo_text)
{
<span>Settings.logo_text</span>
}
最佳答案
official documentation关于新的配置和选项非常好,我建议先看看那里。
按照那里提供的指导,首先为您的设置创建一个 POCO 类:
public class Settings
{
public string logo_text { get; set; }
public bool enable_logo_text { get; set; }
}
更新
ConfigureServices
您的启动类的方法,以便您从配置的配置中读取您的设置,然后可以作为可以在您需要的任何地方注入(inject)的服务:public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<Settings>(Configuration);
services.AddOptions();
}
如果您想使用 appsettings.json 文件,请确保您还构建了
Configuration
包括该 json 文件的对象。例如:public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
这样您就可以在 appsettings.json 文件中配置您的值,这些值将在您的
Settings
上设置。类(class):{
...
"enable_logo_text": true,
"logo_text": "My Logo Text"
}
最后,您可以通过添加
IOptions<Settings>
来访问配置的值。依赖。最直接的方法是将选项直接注入(inject) View (如 the docs 中所述),但您可能需要考虑将选项注入(inject) Controller 并以更可控的方式将它们传递给 View :@inject IOptions<Settings> Settings
...
@if(Settings.Value.enable_logo_text)
{
<span>@Settings.Value.logo_text</span>
}
关于razor - 如何从设置 json 获取数据到 mvc 6 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34127690/