如何在Asp.net Core中缓存资源?

编程入门 行业动态 更新时间:2024-10-26 15:23:20
本文介绍了如何在Asp Core中缓存资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

能给我指出一个例子吗?我想缓存一些将在网站上大多数页面上频繁使用的对象吗?我不确定在MVC 6中推荐的方法是什么.

Can you please point me to an example. I want to cache some objects that will be frequently used in most of the pages on the website? I am not sure what will be the recommended way of doing it in MVC 6.

推荐答案

在startup.cs中:

public void ConfigureServices(IServiceCollection services) { // Add other stuff services.AddCaching(); }

然后在控制器中,将IMemoryCache添加到构造函数中,例如对于HomeController:

Then in the controller, add an IMemoryCache onto the constructor, e.g. for HomeController:

private IMemoryCache cache; public HomeController(IMemoryCache cache) { this.cache = cache; }

然后我们可以使用以下方法设置缓存:

Then we can set the cache with:

public IActionResult Index() { var list = new List<string>() { "lorem" }; this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); // Define options return View(); }

(带有任何选项已设置)

(With any options being set)

并从缓存中读取:

public IActionResult About() { ViewData["Message"] = "Your application description page."; var list = new List<string>(); if (!this.cache.TryGetValue("MyKey", out list)) // read also .Get("MyKey") would work { // go get it, and potentially cache it for next time list = new List<string>() { "lorem" }; this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); } // do stuff with return View(); }

更多推荐

如何在Asp.net Core中缓存资源?

本文发布于:2023-11-13 21:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   如何在   资源   net   Asp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!