我遇到了同样的问题,并找到了问题 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 {... }
这些属性必须一起应用才能正常工作。您还可以通过为每个操作提供相同的规则来控制操作级别的缓存。
我还没有弄清楚问题 1 的解决方案。但是请注意这个空间的更新。
更新
我找到了问题 1 的解决方案。
- 在您的 IoC 容器中注册
CachingHandler(在我的例子中是 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);
}
}