从appsettings.json

时间:2018-08-25 13:39:41

标签: c# .net asp.net-mvc asp.net-core dependency-injection

所以我真的被困了2天。我一直在遵循许多指南来搜索低谷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”处创建断点时,我可以在提供程序和成员中看到我的值存储在其中的记录,因此我想我没有对数组进行正确的调用?总之,如果我被卡住了,那么如果我得到一个很好的工作机会真的会有所帮助:(。

2 个答案:

答案 0 :(得分: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": []
  }
}

答案 1 :(得分:0)

对于WebHost.CreateDefaultBuilder中的Program.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. 在控制器中使用

    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