2017-11-11 100 views
1

我試圖將一個id列表綁定到一個設置,並且它在我使用綁定時起作用,但是使用GetValue檢索它不起作用。即這個工程:.Net Core 2.0配置與列表

var authenticationSettings = new Authentication(); 

this.Configuration.GetSection("Authentication").Bind(authenticationSettings); 

var clients = authenticationSettings.AuthorizedApplications; 

這不:

var authenticationSettings = this.Configuration.GetValue<Authentication>("Authentication"); 

這不起作用

var clients = this.Configuration.GetValue<List<string>>("Authentication:AuthorizedApplications"); 

這裏是我的配置類:

public class Authentication 
{ 
    public List<string> AuthorizedApplications { get; set; } 
} 

回答

1

檢查這篇文章約configuration in ASP.NET Core

GetValue適用於簡單場景,不會綁定到整個 部分。 GetValue從GetSection(key)獲取標量值。值 轉換爲特定類型。

這就是爲什麼你應該使用Bind()擴展方法,該方法提供了將整個配置節綁定到強類型c#對象的功能。

前段時間我開發了下面的擴展方法,允許獲得部分的一行代碼:

public static class ConfigurationExtensions 
{ 
    public static T GetSectionValue<T>(this IConfiguration configuration, string sectionName) where T : new() 
    { 
     var val = new T(); 
     configuration.GetSection(sectionName).Bind(val); 
     return val; 
    } 
} 

var authenticationSettings = Configuration.GetSectionValue<Authentication>("Authentication"); 
var listValue = Configuration.GetSectionValue<List<string>>("Authentication:AuthorizedApplications"); 
+0

這是不必要的。只需使用'Configuration.GetSection(「SectionName」)。獲取();' –