如何在appsetting.json中加载子对象(asp.net core)

时间:2017-02-16 21:17:24

标签: asp.net-core

我正在为ASP.NET Core Web API项目编写一个小的Action Filter。过滤器用于测试关联的UI以进行错误处理。如果调用特定的动词和方法,它将抛出错误。过滤器不是问题。问题是appsettings.configuration。

这是我正在尝试做的事情: 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 个答案:

答案 0 :(得分:2)

更好的选择是在TOption方法中绑定ConfigServices,然后将其注入到文件管理器中。它与默认模型绑定器工作相同,您无需手动读取和设置值。

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;