Reputation: 4733
In my .net core 2.0 application,I have created a appsettings.json file to store the configuration detail for the application.
appsettings.json
{
"RestCalls": {
"SFGetAllAccounts": "https://example.com",
"SFGetIndividualAccount": "https://example.com",
"B6GetAccount": "https://example.com"
}
}
Equivalent .Net Class to Map values
public class AppConfiguration
{
public string SFGetAllAccounts { get; set; }
public string SFGetIndividualAccount { get; set; }
public string B6GetAccount { get; set; }
}
In Startup.cs
Added the following configuration
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
services.Configure<AppConfiguration>(Configuration.GetSection("RestCalls"));
}
In the Controller Class, When Post method is called in the _configuration object is initialized and is blank so all the property from this class AppConfiguration is null.
public class HomeController : Controller
{
private readonly IOptions<AppConfiguration> _configuration;
public HomeController(IOptions<AppConfiguration> config)
{
this._configuration = config;
}
public IActionResult Post([FromBody]LoginModel model)
{
RESTCreatorHelper r = new RESTCreatorHelper(_configuration);
}
}
I have searched a lot about this things on SO and tried many approaches nothing seems to work. Obivously i am missing something can you suggest what is need for the values to be filled in _configuration object and also how should i access the property value.
Upvotes: 3
Views: 1122
Reputation: 4733
The problem was the file was inside a folder and it was not able to find the file . So I corrected the path
var builder =
new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("ConfigurationFiles/AppSettings.json", optional: true, reloadOnChange: true);
and also added AddOptions which binded the values correctly.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AppConfiguration>(Configuration.GetSection("RestCalls"));
services.AddMvc();
}
Upvotes: 3
Reputation: 1200
I think the issue is probably to do with .SetBasePath(env.ContentRootPath)
which I believe will return to the wwwroot
folder within the project and not the project root where appsettings.json
sits.
If that's changed to .SetBasePath(Directory.GetCurrentDirectory())
it will hopefully start working.
I believe that in in asp.net core 1 the content root path was normally set to the current directory when the WebHostBuilder
was created but that's from memory and I could be wrong.
Upvotes: 1