Configuration.GetSection 返回空值。

5

我无法让Configuration.GetSection返回.Value中的数据。 我认为我已经实现了这个问题中的所有建议,但仍然无法使其工作。

appsettings.json

{
    "AmazonSettings": {
       "BaseUrl": "https://testing.com",
       "ClientID": "123456",
       "ResponseType": "code",
       "RedirectUri": "https://localhost:44303/FirstTimeWelcome"
    },
}

创业公司:

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();
}

配置服务:

public void ConfigureServices(IServiceCollection services)
{

    services.AddOptions();

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

    services.AddMvc()

AmazonSettings类:

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

}

我正在尝试通过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;
    }

当我调试时,值为空:

调试 - 值为空


你展示的内容依据 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.1 的文档看起来是准确的。 - Nkosi
这是实际的appsetting还是只是一小段代码(当然不包括安全值)。检查文件格式是否正确。提供一些故障排除选项。 - Nkosi
@Nkosi 检查一下也无妨!这只是一个片段而已。我确认过它的格式是正确的 - 我甚至从 appsettings.json(和 appsettings.Development.json)中删除了除“AmazonSettings”部分之外的所有其他值,但它仍然无法工作...还有其他想法吗? - Danielle Friend
创建一个新的空项目,添加设置并查看是否读取。 - Nkosi
你在调试中看到了什么环境? - Dmitry Pavlov
1个回答

0
我的问题是HomeController中的代码从来没有被执行过。
如果我在控制器上方添加Routes [“home”]并导航到localhost / home,则可以到达那里,并且.Value已经填充。但是,由于我正在使用Razor页面,因此无法使用Routes [“”],因为这会导致ambiguousActionException。
然后我意识到在Razor Pages中根本不需要使用控制器。我可以直接从Index.cshtml.cs访问我的数据。
public class IndexModel : PageModel
    private readonly AmazonSettings _amazonSettings;
    public string LoginUrl;

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

在我的Index.cshtml页面中,具有以下访问方式:
<a href=@Model.LoginUrl><h1>@Model.LoginUrl</h1></a>

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接