Configuration.GetSection 返回空值

Dan*_*end 5 c# asp.net-core asp.net-core-configuration

我无法让我Configuration.GetSection返回.Value. 我想我实施了这个问题的所有建议,但仍然无法让它发挥作用。

appsettings.json

{
    "AmazonSettings": {
       "BaseUrl": "https://testing.com",
       "ClientID": "123456",
       "ResponseType": "code",
       "RedirectUri": "https://localhost:44303/FirstTimeWelcome"
    },
}
Run Code Online (Sandbox Code Playgroud)

启动:

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();
}
Run Code Online (Sandbox Code Playgroud)

配置服务:

public void ConfigureServices(IServiceCollection services)
{

    services.AddOptions();

    services.Configure<AmazonSettings>(Configuration.GetSection("AmazonSettings"));

    services.AddMvc()
Run Code Online (Sandbox Code Playgroud)

AmazonSettings 类:

public class AmazonSettings
{
    public string BaseUrl { get; set; }
    public string ClientID { get; set; }
    public string RedirectUri { get; set; }
    public string ResponseType { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试通过 IOptions 访问 AmazonSettings.Value:

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;
    }
Run Code Online (Sandbox Code Playgroud)

当我调试时,值为空:

调试 - 值为空

Dan*_*end 0

我的问题是我在 HomeController 中的代码从未被命中。

如果我在控制器上方添加 Routes["home"] 并导航到 localhost/home,我就可以到达那里,并且 .Value 已填充。但是,我无法使用 Routes[""],因为我使用的是 Razor 页面,这导致了 ambigeousActionException。

然后我意识到我根本不需要在 Razor Pages 中使用控制器。我可以直接从 Index.cshtml.cs 访问我的数据

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

    public IndexModel(IOptions<AmazonSettings> amazonSettings)
    {
        _amazonSettings = amazonSettings.Value;
    }
Run Code Online (Sandbox Code Playgroud)

在我的 Index.cshtml 页面中进行以下访问:

<a href=@Model.LoginUrl><h1>@Model.LoginUrl</h1></a>
Run Code Online (Sandbox Code Playgroud)

事实证明,在调试时,启动代码中 GetSection 返回的 .Value 可能为 null,但在到达 IndexModel 时它会被填充。