razor - 如何从设置 json 获取数据到 mvc 6 View ?

标签 razor json.net asp.net-core-mvc

我想一次从 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/

相关文章:

javascript - jQuery-将更改事件添加到Html.DropDownList

c# - 使用 Web API 和 JSON.NET 序列化对象时防止 $id/$ref

c# - TagHelper 从 ForExpression 获取 MaxLengthAttribute 属性

c# - .NET Core 2.0 MVC 文件上传进度

c# - Asp.Net MVC Razor BootStrap 输入表单

asp.net - 如何将占位符属性与 Html.EditorFor 一起使用?

c# - 当 JsonConstructor 参数名称与 JSON 不匹配时如何抛出异常?

iis-express - 使用 VS2015 和 IIS Express 覆盖站点绑定(bind)

ASP.net MVC - 在区域之间共享部分

c# - 如何在 C# 中使用 Newtonsoft 反序列化