2017-09-15 28 views
1

我知道如何爲appsettings.json配置服務並將它們注入到控制器中。不過,我需要在配置身份驗證時使用ConfigureServices中的值。我將如何做到這一點?請參閱下面的示例。特別是這一行:在startup.cs中訪問appsetting.json值

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

回答

1

你可以訪問此ConfigureServices方法類似這樣的

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

上面的代碼工作,你需要與客戶端Id有POCO類稱爲AADSettings作爲屬性

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

和appsettings.json文件,你需要有這樣的條目

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

假設你appsettings.json你有它這樣的節點下:

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

,那麼你應該能夠訪問它通過以下代碼

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