HttpRuntime.Cache Equivalent for asp.net 5, MVC 6

情到浓时终转凉″ 提交于 2019-12-03 18:11:11

问题


So I've just moved from ASP.Net 4 to ASP.Net 5. Im at the moment trying to change a project so that it works in the new ASP.Net but of course there is going to be a load of errors.

Does anyone know what the equivalent extension is for HttpRuntime as I cant seem to find it anywhere. I'm using to cache an object client side.

HttpRuntime.Cache[Findqs.QuestionSetName] 

'Findqs' is just a general object


回答1:


You can an IMemoryCache implementation for caching data. There are different implementations of this including an in-memory cache, redis,sql server caching etc..

Quick and simple implemenation goes like this

Update your project.json file and add the below 2 items under dependencies section.

"Microsoft.Extensions.Caching.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final"

Saving this file will do a dnu restore and the needed assemblies will be added to your project.

Go to Startup.cs class, enable caching by calling the services.AddCaching() extension method in ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCaching();
    services.AddMvc();
}

Now you can inject IMemoryCache to your lass via constructor injection. The framework will resolve a concrete implementation for you and inject it to your class constructor.

public class HomeController : Controller
{
    IMemoryCache memoryCache;
    public HomeController(IMemoryCache memoryCache)
    {
        this.memoryCache = memoryCache;
    }
    public IActionResult Index()
    {   
        var existingBadUsers = new List<int>();
        var cacheKey = "BadUsers";
        List<int> badUserIds = new List<int> { 5, 7, 8, 34 };
        if(memoryCache.TryGetValue(cacheKey, out existingBadUsers))
        {
            var cachedUserIds = existingBadUsers;
        }
        else
        {
            memoryCache.Set(cacheKey, badUserIds);
        }
        return View();
    }
} 

Ideally you do not want to mix your caching within your controller. You may move it to another class/layer to keep everything readable and maintainable. You can still do the constructor injection there.

The official asp.net mvc repo has more samples for your reference.



来源:https://stackoverflow.com/questions/34414310/httpruntime-cache-equivalent-for-asp-net-5-mvc-6

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