Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

c# - HttpRuntime.Cache Equivalent for asp.net 5, MVC 6

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...