簡體   English   中英

存儲和訪問Controller中對象列表的最佳方法

[英]Best way to store and access List of Objects in Controller

我使用webservice從其他應用程序獲取用戶列表。 我收到了所有的信息。

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

我想在控制器操作之間存儲這個用戶列表,這樣我就不想每次都為他們的角色和其他信息點擊Web服務。

使用C#和MVC這是最好的方法

您可以使用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的選項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM