简体   繁体   中英

Using Cache ASP.NET

如何在ASP.NET中使用所有用户都可以访问的缓存,而不仅仅是特定的用户上下文,同时当用户关闭浏览器窗口或过期(如会话对象)时自动删除此缓存的特定键吗?

Cache is accessible to all users, you can set it to expire after a period of time:

Cache.Insert("key", myTimeSensitiveData, null, 
DateTime.Now.AddMinutes(1), TimeSpan.Zero);

You may remove the cache entry whenever a session expires by implementing the global.asax's session end event

void Session_End(Object sender, EventArgs E) 
{ 
  Cache.Remove("MyData1");
}

See this for more details on Cache

Edited: Regarding your question on how to react when the user closes its browser, I think that this is not straightforward. You could try javascript on the client side to handle the "unload" event but this is not reliable since the browser/client may just crash. In my opinion the "heartbeat" approach would work but it requires additional effort. See this question for more info.

You'll have to use the Session_OnEnd() event to remove the item from the cache. However, this event will not fire if the user just closes the browser. The event will only fire on the session timeout. You should probably add a check to see if the item has already been removed:

public void Session_OnEnd()
{
    // You need some identifier unique to the user's session
    if (Cache["userID"] != null)
        Cache.Remove("userID");
}

Also, if you want the item in the cache to stay active for the duration of the user's session, you'll need to use a sliding expiration on the item and refresh it with each request. I do this in the OnActionExecuted (ASP.NET MVC only).

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    // Put object back in cache in part to update any changes
    // but also to update the sliding expiration
    filterContext.HttpContext.Cache.Insert("userID", myObject, null, Cache.NoAbsoluteExpiration,
        TimeSpan.FromMinutes(20), CacheItemPriority.Normal, null);

    base.OnActionExecuted(filterContext);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM