如何在 ASP.NET MVC 中缓存对象? [英] How can I cache objects in ASP.NET MVC?

查看:21
本文介绍了如何在 ASP.NET MVC 中缓存对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 ASP.NET MVC 中缓存对象.我有一个 BaseController 我希望所有控制器都继承它.在 BaseController 中有一个 User 属性,它会简单地从数据库中获取用户数据,以便我可以在控制器中使用它,或者将其传递给视图.

I'd like to cache objects in ASP.NET MVC. I have a BaseController that I want all Controllers to inherit from. In the BaseController there is a User property that will simply grab the User data from the database so that I can use it within the controller, or pass it to the views.

我想缓存此信息.我在每个页面上都使用此信息,因此无需在每个页面请求中访问数据库.

I'd like to cache this information. I'm using this information on every single page so there is no need to go to the database each page request.

我想要类似的东西:

if(_user is null)
  GrabFromDatabase
  StuffIntoCache
return CachedObject as User

如何在 ASP.NET MVC 中实现简单的缓存?

How do I implement simple caching in ASP.NET MVC?

推荐答案

您仍然可以使用缓存(在所有响应之间共享)和会话(每个用户唯一)进行存储.

You can still use the cache (shared among all responses) and session (unique per user) for storage.

我喜欢下面的尝试从缓存中获取/创建和存储"模式(类似 c# 的伪代码):

I like the following "try get from cache/create and store" pattern (c#-like pseudocode):

public static class CacheExtensions
{
  public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator)
  {
    var result = cache[key];
    if(result == null)
    {
      result = generator();
      cache[key] = result;
    }
    return (T)result;
  }
}

你会这样使用它:

var user = HttpRuntime
              .Cache
              .GetOrStore<User>(
                 $"User{_userId}", 
                 () => Repository.GetUser(_userId));

您可以将此模式应用于 Session、ViewState(呃)或任何其他缓存机制.您还可以扩展 ControllerContext.HttpContext(我认为它是 System.Web.Extensions 中的包装器之一),或者创建一个新类来完成它,并留出一些空间来模拟缓存.

You can adapt this pattern to the Session, ViewState (ugh) or any other cache mechanism. You can also extend the ControllerContext.HttpContext (which I think is one of the wrappers in System.Web.Extensions), or create a new class to do it with some room for mocking the cache.

这篇关于如何在 ASP.NET MVC 中缓存对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆