简体   繁体   English

使用缓存ASP.NET

[英]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 您可以通过实现global.asax的会话结束事件,在会话过期时删除缓存条目

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. 您可以在客户端尝试使用javascript处理“卸载”事件,但这不可靠,因为浏览器/客户端可能会崩溃。 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. 您必须使用Session_OnEnd()事件从缓存中删除该项目。 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). 我在OnActionExecuted(仅限ASP.NET MVC)中执行此操作。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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