且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 ASP.NET MVC 中缓存对象?

更新时间:2022-11-23 12:18:07

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

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.