将缓存配置文件设置移动到ASP.NET Core中的appsettings.json

时间:2015-08-07 09:53:51

标签: asp.net-core asp.net-core-mvc

我希望能够在config.json文件中编辑缓存配置文件设置。您可以使用web.config文件在ASP.NET 4.6中执行类似的操作。这就是我现在所拥有的:

services.ConfigureMvc(
    mvcOptions =>
    {
        mvcOptions.CacheProfiles.Add(
            "RobotsText",
            new CacheProfile()
            {
                Duration = 86400,
                Location = ResponseCacheLocation.Any,
                // VaryByParam = "none" // Does not exist in MVC 6 yet.
            });
    });

我想做这样的事情:

services.ConfigureMvc(
    mvcOptions =>
    {
        var cacheProfiles = ConfigurationBinder.Bind<Dictionary<string, CacheProfile>>(
            Configuration.GetConfigurationSection("CacheProfiles"));
        foreach (var keyValuePair in cacheProfiles)
        {
            mvcOptions.CacheProfiles.Add(keyValuePair);
        }
    });

我的appsettings.json文件看起来像这样:

{
  "AppSettings": {
    "SiteTitle": "ASP.NET MVC Boilerplate"
  }
  "CacheProfiles" : {
    "RobotsText" : {
      "Duration" : 86400,
      "Location" : "Any",
    }
  }
}

然而,我无法让它发挥作用。尝试绑定配置部分时,我一直收到反射错误。

1 个答案:

答案 0 :(得分:2)

示例:

public class CacheProfileSettings
{
    public Dictionary<string, CacheProfile> CacheProfiles { get; set; }
}

//------------------------------------------

var cacheProfileSettings = ConfigurationBinder.Bind<CacheProfileSettings>(config.GetConfigurationSection("CacheProfiles"));
var cacheProfile = cacheProfileSettings.CacheProfiles["RobotsText"];