2017-09-15 116 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"]