Configuration.GetSection returns null value

眉间皱痕 提交于 2019-12-23 20:23:15

问题


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:


回答1:


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 href=@Model.LoginUrl><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.



来源:https://stackoverflow.com/questions/50669724/configuration-getsection-returns-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!