繁体   English   中英

从appsettings.json检索数据

[英]Retrieving data from appsettings.json

所以我真的被困了两天。 我一直在遵循许多指南来搜索低谷stackoverflow和谷歌,但没有帮助:/。 所以我正在尝试从appsettings json文件中检索数据,因为我会将数据存储在其中作为我的标准设置文件。

我想读取一个json数组-> iv',称为我的“位置”部分和我的键“ Location”,其中我的值是一个json数组。 目前,该阵列中只有汽车公司名称,而没有真实数据。 实际数据是文件路径。

我正在将vs2017与.net core 2.0或2.1一起使用

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; set; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddJsonOptions(config =>
        {
            config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });
    services.AddOptions();
    services.AddSingleton<IConfiguration>(Configuration);


}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();

    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    Configuration = builder.Build();
}

这是我的入门班。

"Locations": {
    "Location": [ "Ford", "BMW", "Fiat" ]
}, 

我的json。

namespace MediaCenter.Models
{
    public class Locations
    {
        public List<string> location { get; set; }
    }
}

自从我读到它对于DI系统的.net core 2.0来说是需要的。

public IActionResult Settings()
{
    var array = _configuration.GetSection("Locations").GetSection("Location");
    var items = array.Value.AsEnumerable();
    return View();
}

我的控制器数据。

作为记录,当我在“ var array”处创建断点时,我可以在提供程序和成员中看到我的值存储在其中,因此我想我没有对数组进行正确的调用? 总之,如果我被卡住:(。

有几处错误。

  1. 在启动时,您需要在构造函数中配置Configuration而不是在ConfigureServices(services)
  2. 它们存储为Children ,因此您需要在您的部分中执行GetChildren()

这是您需要在Startup.cs进行的更改

// Replace IConfiguration with IHostingEnvironment since we will build
// Our own configuration
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    // Set the new Configuration
    Configuration = builder.Build();
}

现在,您可以在控制器中使用以下命令:

public IActionResult Settings()
{
   var array = Configuration.GetSection("Locations:Location")
       .GetChildren()
       .Select(configSection => configSection.Value);
   return View();
} 

编辑

问题是appsettings.json的格式不正确。 一切都配置为“ Logging部分的子级。 以下是更新和正确的json,我添加了一个额外的},并从底部删除了}

 {
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "DBConnection": {
    "Host": "",
    "UserName": "",
    "Password": ""
  },

  "Locations": {
    "Location": [ "Ford", "BMW", "Fiat" ]
  },

  "VideoExtensions": {
    "Extensions": []
  }
}

对于Program.cs WebHost.CreateDefaultBuilder ,无需使用new ConfigurationBuilder() 尝试以下选项:

Option1IConfiguration获取价值

    public class OptionsController : Controller
{
    private readonly IConfiguration _configuration;

    public OptionsController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public IActionResult Index()
    {
        var locations = new Locations();
        _configuration.GetSection("Locations").Bind(locations);

        var items = locations.location.AsEnumerable();
        return View();
    }
}

选项配置OptionsStartup

  1. Startup.cs

      services.Configure<Locations>(Configuration.GetSection("Locations")); 
  2. 在控制器中使用

     public class OptionsController : Controller { private readonly Locations _locations; public OptionsController(IOptions<Locations> options) { _locations = options.Value; } public IActionResult Index() { var items2 = _locations; return View(); } } 

源代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM