I am trying to access AppSettings as service in my ASP.NET core WebAPI. When I do Configuration.GetSection("AppSettings") I get null but I could access the configuration values as Configuration["AppSettings:StorageConnectionKey:AccountName"]. I am not sure what I am doing wrong.
My Startup.cs is shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Library;
namespace Athraya
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
// .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
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)
{
// Add framework services.
services.AddMvc();
services.AddOptions();
services.Configure<AppSettings>(options => Configuration.GetSection("AppSettings"));
// *If* you need access to generic IConfiguration this is **required**
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, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
}
and my appsetting is
{
"AppSettings": {
"StorageConnectionKey": {
"AccountName": "myaccountName",
"AccountKey": "abc"
},
"CloudContainerkey": {
"ContainerName": "mycontainername",
"FileName": "db.dat"
}
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
I have a Library Project where I have the classes needed
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public class AppSettings
{
public StorageConnectionKey storageKey {get; set; }
public CloudContainerKey containerKey { get; set; }
}
}
namespace Library
{
public class CloudContainerKey
{
public string ContainerName { get; set; }
public string FileName { get; set; }
}
}
namespace Library
{
public class StorageConnectionKey
{
public string AccountName { get; set; }
public string AccountKey { get; set; }
}
}
I am trying to get it in controller as
public class ValuesController : Controller
{
private readonly AppSettings _appSettings;
public ValuesController(IOptions<AppSettings> settings)
{
_appSettings = settings.Value;
}
}
Any Help here is appreciated.