2017-02-16 53 views
0

我正在爲ASP.NET Core web API項目編寫一個小動作過濾器。該過濾器用於測試關聯的UI以進行錯誤處理。如果調用特定的動詞和方法,它會引發錯誤。過濾器不是問題。問題是appsettings.configuration。如何加載appsetting.json中的子對象(asp.net核心)

這裏的我想要做什麼: appsettings.development.json

"FaultTesting": { 
    "FaultRequests": false, 
    "SlowRequests": 0, 
    "FaultCalls": [ 
     { 
     "Path": "/api/usercontext", 
     "Verbs": "get,put,delete" 
     }, 
     { 
     "Path": "/api/cafeteriaaccounts", 
     "Verbs": "get" 
     } 
    ] 
    } 

這是我的C#類型來控制配置:

public class FaultTestingOptions 
    { 
     /// <summary> 
     /// If true, checks FaultCalls for a path and verb to match. 
     /// </summary> 
     public bool FaultRequests { get; set; } 

     /// <summary> 
     /// Number of milliseconds to delay the response. 
     /// </summary> 
     public int SlowRequests { get; set; } 

     public FaultCall[] FaultCalls { get; set; } 

    } 
    public class FaultCall 
    { 
     public string Path { get; set; } 

     public string Verbs { get; set; } 
    } 

添加什麼我正在做啓動:

  services.AddMvc(config => 
       { 
... 
FaultTestingFilter(Options.Create(GetFaultTestingOptions()))); 
... 
       }); 

private FaultTestingOptions GetFaultTestingOptions() 
{ 
    var options = new FaultTestingOptions 
    { 
     FaultRequests = Configuration["FaultTesting:FaultRequests"].ToBoolean(), 
     SlowRequests = Convert.ToInt32(Configuration["FaultTesting:SlowRequests"]) 
    }; 

    var calls = Configuration.GetSection("FaultTesting:FaultCalls") 
     .GetChildren() 
     .Select(x => x.Value) 
     .ToArray(); 

    var fooie = Configuration["FaultTesting:FaultCalls"]; 


    //options.FaultCalls = calls.Select(c => new FaultCall { Path = c, Verbs = c.Value }); 

    return options; 
} 

「calls」是一個由兩個空值組成的數組,fooie爲null。

這裏有什麼正確的方法?

回答

1

更好的選擇是綁定TOptionConfigServices方法,然後將其注入到您的文件管理器。它與默認模型活頁夾工作相同,您不需要手動讀取和設置值。

ConfigureServices方法:

public void ConfigureServices(IServiceCollection services) 
{ 
    services.Configure<FaultTestingOptions>(option => Configuration.GetSection("FaultTesting").Bind(option)); 
    // Add framework services. 

    services.AddMvc(); 
} 

在過濾器注射:

private readonly IOptions<FaultTestingOptions> config; 

public FaultTestingFilter(IOptions<FaultTestingOptions> config) 
{ 
    this.config = config; 
} 

訪問屬性。

var SlowRequests= config.Value.SlowRequests; 
var FaultCalls= config.Value.FaultCalls; 
+0

這工作得很好。感謝您的解決方案。 – Elton