Moving Cache Profiles Settings to appsettings.json in ASP.NET Core

霸气de小男生 提交于 2019-12-08 10:22:49

问题


I would like to be able to edit the cache profile settings in my config.json file. You could do something similar in ASP.NET 4.6 with the web.config file. This is what I have now:

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

I would like to do something like this:

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

With my appsettings.json file looking like this:

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

However, I have not been able to get this to work. I keep getting reflection errors upon trying to bind the configuration section.


回答1:


Example:

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

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

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


来源:https://stackoverflow.com/questions/31874849/moving-cache-profiles-settings-to-appsettings-json-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!