So I'm really stuck for 2 days. I've been searching trough stackoverflow and google following many guides but non that helped :/. So I'm trying to retrieve data from the appsettings json file as i will store data in there as my standard settings file.
I want to read a json array-> iv' called my section "Locations" and my key "Location" where my values is an json array. For the moment there are only car company names in that array not the real data. The real data are filepaths.
I'm using vs2017 with .net core 2.0 or 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();
}
This is my startup class.
"Locations": {
"Location": [ "Ford", "BMW", "Fiat" ]
},
my json.
namespace MediaCenter.Models
{
public class Locations
{
public List<string> location { get; set; }
}
}
My class for it since I read that it's needed for .net core 2.0 for the DI system.
public IActionResult Settings()
{
var array = _configuration.GetSection("Locations").GetSection("Location");
var items = array.Value.AsEnumerable();
return View();
}
my controller data.
For the record when i make a breakpoint at "var array" i can see in the providers and members that my values are stored within so i guess i'm not making the proper call to the array? anayways it would really help if I get a good working asnwer since i'm stuck :(.
There are a couple things wrong.
Configuration
in your constructor not in the ConfigureServices(services)
. Children
, so you need to do GetChildren()
on your section. Here is what you need to change in 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();
}
In your controller you can now use the following:
public IActionResult Settings()
{
var array = Configuration.GetSection("Locations:Location")
.GetChildren()
.Select(configSection => configSection.Value);
return View();
}
Edit
Problem is that the appsettings.json is formatted incorrectly. Everything was configured as a child of the Logging
Section. Below is the updated and correct json, I added an extra },
and removed }
from the bottom.
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"DBConnection": {
"Host": "",
"UserName": "",
"Password": ""
},
"Locations": {
"Location": [ "Ford", "BMW", "Fiat" ]
},
"VideoExtensions": {
"Extensions": []
}
}
For WebHost.CreateDefaultBuilder
in Program.cs
, there is no need to use new ConfigurationBuilder()
. Try options below:
Option1 Get value from 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 Configure Options
in Startup
Startup.cs
services.Configure<Locations>(Configuration.GetSection("Locations"));
Use in 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(); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.