以编程方式清除ASP.NET Core中的缓存配置文件

以编程方式清除ASP.NET Core中的缓存配置文件

问题描述:

我已经在asp.net核心Web API中设置了缓存配置文件,如下所示:

I have setup a cache profile in my asp.net core web api as follows:

services.AddMvc(options => {
     // Cache profile for lookup data will expire every 15 minutes.
     options.CacheProfiles.Add("LookupData", new CacheProfile() { Duration = 15 });    
});

我已在"lookupsController"的顶部使用了此属性,因为每种方法返回的信息列表不会定期更改(尽管缓存每15分钟自动过期一次).

I have used this attribute at the top of my "lookupsController", as the lists of information returned in each method won't change regularly (although cache automatically expires every 15 minutes).

[ResponseCache(CacheProfileName = "LookupData")]
[Produces("application/json")]
[Route("api/Lookups")]
public class LookupsController : Controller
{
    ...
}

我还有另一个管理控制器,该控制器可以允许用户添加和删除查找控制器列表中的项目,这种情况通常不会发生,但是当发生这种情况时,我想以编程方式强制缓存配置文件重置并强制随后的Web请求获取最新的数据,而不是保留现在过时的缓存数据列表.

I have another admin controller which can allow users to add and remove items in the lookups controller list, this won't happen often but when it does, I want to programmatically force the cache profile to reset and force subsequent web requests to get the latest, rather than keeping the now outdated cached list of data.

如何以编程方式实现缓存的重置? -然后,我可以将此代码添加到我的管理控制器方法中,以强制重置缓存.有人曾经做过吗?

How do I achieve the resetting of cache programmatically? - I can then add this code into my admin controller methods, to force cache resetting. Has anyone had to do this before?

您无法真正清除该缓存,因为它不是服务器而是客户端缓存. ResponseCache属性将仅设置某些标头作为响应.简化说明:浏览器(或任何中间代理)向您的api发出请求时,注意到那些响应标头,看到此响应在15分钟内有效,因此在接下来的15分钟内不会重复该请求,而是从该请求中获取该响应. 本地缓存.由于您无法控制该本地缓存,因此无法清除它.

You cannot really clear that cache, because it's not server but client cache. ResponseCache attribute will just set certain headers in response. Simplified description of how this works: browser (or any intermediate proxy) making request to your api notice those response headers, sees that this response is valid for 15 minutes and so will not repeat that request for the next 15 minutes instead taking it from its local cache. Since you have no control over that local cache - you cannot clear it.