Configuration.GetSection returns null value

5.3k views Asked by At

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:

Debug - Value is empty

1

There are 1 answers

0
Danielle Friend On BEST ANSWER

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

public class IndexModel : PageModel
    private readonly AmazonSettings _amazonSettings;
    public string LoginUrl;

    public IndexModel(IOptions<AmazonSettings> amazonSettings)
    {
        _amazonSettings = amazonSettings.Value;
    }

With the following access in my Index.cshtml page:

<a [email protected]><h1>@Model.LoginUrl</h1></a>

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.