从appsettings.json中检索数据

问题描述 投票:0回答:2

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

我想读一个json数组 - > iv'调用我的部分“Locations”和我的键“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”处创建一个断点时,我可以在提供者和成员中看到我的值存储在其中,所以我想我没有对数组进行正确的调用?因为我被困住了,所以如果我得到一个好的工作,它会真的有帮助:(。

c# .net asp.net-mvc asp.net-core dependency-injection
2个回答
0
投票

有几件事是错的。

  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": []
  }
}

0
投票

对于WebHost.CreateDefaultBuilderProgram.cs,没有必要使用new ConfigurationBuilder()。尝试以下选项:

选项1从IConfiguration获取价值

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

选项在Options中配置Startup

  1. Startup.cs services.Configure<Locations>(Configuration.GetSection("Locations"));
  2. 在Controller中使用 public class OptionsController : Controller { private readonly Locations _locations; public OptionsController(IOptions<Locations> options) { _locations = options.Value; } public IActionResult Index() { var items2 = _locations; return View(); } }

Source Code

© www.soinside.com 2019 - 2024. All rights reserved.