【问题标题】:Best way to store and access List of Objects in Controller在控制器中存储和访问对象列表的最佳方式
【发布时间】:2015-04-30 12:26:18
【问题描述】:

我正在使用 web 服务从其他应用程序获取用户列表。我正在获取所有信息。

  List<User> users = ws.SelectUsers();

我想将此用户列表存储在控制器操作之间,这样我就不想每次都为他们的角色和其他信息点击 Web 服务。

使用 C# 和 MVC 的最佳方法是什么

我想

【问题讨论】:

  • 这个列表是用户独有的还是应用程序共有的?
  • Asp.net Http Cache 对我有用。
  • 是的。由于有人不可避免地会在这里插话并告诉您使用SessionTempData,所以让我们把它从开头剪掉,并说缓存Web 服务调用的结果。然后,对于每个请求,您检查该数据的缓存,如果存在则使用它,如果不存在则再次调用 Web 服务来填充它。
  • @Ako 为什么不用那个回答? :)

标签: c# asp.net-mvc-4


【解决方案1】:

您可以使用 MemoryCache 来存储东西。下面的示例将用户在缓存中存储一​​个小时。如果您需要基于每个用户存储它,您可以稍微更改它,以便使用用户 ID 或其他内容生成缓存键(以下示例中的“用户”)。

MemoryCache cache = MemoryCache.Default;
string baseCacheKey = "Users";

public void DoSomethingWithUsers(int userId)
{
    var cacheKey = baseCacheKey + userId.ToString();
    if (!cache.Contains(cacheKey))
    {
        RefreshUserCache(userId);
    }
    var users = cache.Get(cacheKey) as List<User>

    // You can do something with the users here
}

public static RefreshUserCache(int userId)
{
    var users = ws.SelectUsers();

    var cacheItemPolicy = new CacheItemPolicy();
    cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1);
    var cacheKey = baseCacheKey + userId.ToString();
    cache.Add(cacheKey, users , cacheItemPolicy);
}

编辑:如果您确实想为每个用户执行此操作,我已经包含了 userId 的选项

【讨论】:

    猜你喜欢
    • 2015-07-19
    • 2019-01-03
    • 1970-01-01
    • 2015-05-10
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    相关资源
    最近更新 更多