gpt4 book ai didi

c# - 访问 startup.cs 中的 appsetting.json 值

转载 作者:太空狗 更新时间:2023-10-29 17:30:02 25 4
gpt4 key购买 nike

我了解如何为 appsettings.json 配置服务并将它们注入(inject) Controller 。但是,我需要在配置 Auth 时使用 ConfigureServices 中的值。我该怎么做?请参阅下面的示例。特别是这一行:

option.clientId = /*Need client Id from appsettings.json*/

代码:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<AADSettings>(Configuration.GetSection("AADSettings"));
services.Configure<APISettings>(Configuration.GetSection("APISettings"));

// Add Authentication services.
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
// Configure the OWIN pipeline to use cookie auth.
.AddCookie()
// Configure the OWIN pipeline to use OpenID Connect auth.
.AddOpenIdConnect(option =>
{
option.clientId = /*Need client Id from appsettings.json*/

option.Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed,
};
});
}

最佳答案

您可以像这样访问此 ConfigureServices 方法

var config = Configuration.GetSection("AADSettings").Get<AADSettings>();
option.clientId = config.ClientId;

要使上述代码正常工作,您需要将 ClientId 作为属性的名为 AADSettings 的 POCO 类

public class AADSettings
{
public string ClientId { get; set; }
}

在 appsettings.json 文件中,你需要有这样的条目

"AADSettings": {
"ClientId": "Client1",
}

关于c# - 访问 startup.cs 中的 appsetting.json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46230582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com