在startup.cs中访问appsetting.json值

时间:2017-09-15 01:59:18

标签: c# asp.net-core-2.0

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

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

代码:

sugar::probs_t

3 个答案:

答案 0 :(得分:13)

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

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

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

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

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

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

答案 1 :(得分:7)

假设在你的appsettings.json中你有这样的节点:

"option": {
  "clientId": "example client id"
}

然后您应该可以通过以下代码访问它

option.clientId = Configuration["option:clientId"]

答案 2 :(得分:3)

Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    
    public IConfiguration Configuration { get; }
    

    public void ConfigureServices(IServiceCollection services)
    {
   
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment)
    {
         User = Configuration.GetSection("HangfireSettings:UserName").Value,
         Pass = Configuration.GetSection("HangfireSettings:Password").Value
    }
}

appsettings.json:

  "HangfireSettings": {
    "UserName": "admin",
    "Password": "admin"
  },