I cannot get my Configuration.GetSection
to return data in .Value
. I think I implemented all the suggestions from this question, but still can't get it to work.
appsettings.json
{
"AmazonSettings": {
"BaseUrl": "https://testing.com",
"ClientID": "123456",
"ResponseType": "code",
"RedirectUri": "https://localhost:44303/FirstTimeWelcome"
},
}
Startup:
public IConfiguration Configuration { get; }
public Startup(IHostingEnvironment env)
{
//Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
ConfigurationServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AmazonSettings>(Configuration.GetSection("AmazonSettings"));
services.AddMvc()
AmazonSettings Class:
public class AmazonSettings
{
public string BaseUrl { get; set; }
public string ClientID { get; set; }
public string RedirectUri { get; set; }
public string ResponseType { get; set; }
}
I'm attempting to access AmazonSettings.Value via IOptions:
public class HomeController : Controller
{
private readonly AmazonSettings _amazonSettings;
public IActionResult Index()
{
ViewBag.LoginUrl = _amazonSettings.BaseUrl;
return View("/Pages/Index.cshtml"); ;
}
public HomeController(IOptions<AmazonSettings> amazonSettings)
{
_amazonSettings = amazonSettings.Value;
}
When I debug, Value is empty:
My problem was that my code in HomeController was never getting hit.
I could get there, and .Value was populated, if I added Routes["home"] above my controller and navigated to localhost/home. I couldn't use Routes[""] however because I'm using Razor pages and this caused an ambiguousActionException.
I then realized I didn't need to use a controller at all with Razor Pages. I could just access my data directly from Index.cshtml.cs
With the following access in my Index.cshtml page:
It turns out that when debugging, the .Value returned by GetSection in the Startup code may be null, however it is populated by the time it reaches the IndexModel.