jvr*_*nte 14 c# caching asp.net-web-api cachecow
我正在尝试使用CacheCow实现缓存.我有两个问题:
在某些情况下,我需要手动使某些资源的缓存无效.
例如,我有一个被调用的资源purchase
,以及一个被调用的资源pointMovements
.他们并没有完全联系,但是做一个帖子purchase
,意味着一些变化pointMovement
.Cachecow没有检测到这些更改,因为我没有调用它的API pointmovements
.因此,当我调用端点时pointmovements
,值被缓存,我无法获得新值.
要解决这个问题,我需要手动使其失效,这怎么可能?
有些控制器我不想缓存.我试图使用属性来做到这一点,但它不起作用.我正在关注这篇文章,但忽略了这些属性.
如何指定要缓存的控制器?
我遇到了同样的问题并找到问题2的解决方案(无论默认设置如何都禁用缓存).
// This forces the server to not provide any caching by refreshing its cache table immediately (0 sec)
[HttpCacheRefreshPolicy(0)]
// This forces the client (browser) to not cache any data returned from the server (even if ETag is present) by setting the time-out to 0 and no-cache to true.
[HttpCacheControlPolicy(true, 0, true)]
public void MyController : ApiControler {... }
Run Code Online (Sandbox Code Playgroud)
必须同时应用这些属性才能使其生效.您还可以通过为每个操作提供相同的规则来控制操作级别的缓存.
我仍然要找出问题1的解决方案,但请注意这个空间的更新.
更新 我找到了问题1的解决方案.
CachingHandler
您的IoC容器(在我的情况下IUnityContainer
)ICachingHandler
Web API控制器.ICachingHandler.InvalidateResource(HttpRequestMessage)
请参阅下面的代码示例.该解决方案已经过测试.
public class Bootstrapper
{
//...
// Create a new caching handler and register it with the container.
public void RegisterCache(HttpConfiguration config, IUnityContainer container)
{
var cachingHandler = new CachingHandler(config);
// ...
container.RegisterInstance<ICachingHandler>(cachingHandler);
}
}
public class ResourceContoller : ApiController
{
private ICachingHandler _cachingHandler;
public ResourceContoller(ICachingHandler cachingHandler)
{
_cachingHandler = cachingHandler;
}
[HttpPost]
public void DeleteResource(int resourceId)
{
// Do the delete
// ...
// Now invalidate the related resource cache entry
// Construct a http request message to the related resource
// HINT: The "DefaultApi" may not be your api route name, so change this to match your route.
// GOTCHA: The route matching mechanism is case sensitive, so be aware!
var relatedResource = new HttpRequestMessage(HttpMethod.Get, Url.Link("DefaultApi", new {controller = "linkedresource", action = "getlinkedresource", id: resourceId}));
// Invalidate the resource with the caching handler.
_cachingHandler.InvalidateResource(relatedResource);
}
}
Run Code Online (Sandbox Code Playgroud)