WCF REST JSON服务缓存 [英] WCF REST JSON service caching
问题描述
我有一个WCF Web服务返回JSON。
I have a WCF web service returning JSON.
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
Stream GetStuff(int arg);
和我使用这个方法的对象图转换为JSON:
And I'm using this method to convert an object graph to JSON:
private static Stream ToJson(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);
if (WebOperationContext.Current != null)
{
OutgoingWebResponseContext outgoingResponse = WebOperationContext.Current.OutgoingResponse;
outgoingResponse.ContentType = "application/json; charset=utf-8";
outgoingResponse.Headers.Add(HttpResponseHeader.CacheControl, "max-age=604800"); // one week
outgoingResponse.LastModified = DateTime.Now;
}
return new MemoryStream(Encoding.UTF8.GetBytes(json));
}
我想响应被缓存的浏览器,但浏览器仍然产生如果修改 - 因为
调用这些重播与<$服务器C $ C> 304未修改。我想在浏览器缓存,并使用响应不必每次都作出如果修改 - 因为
调用服务器。
I'd like the responses to be cached on the browser, but the browser is still generating If-Modified-Since
calls to the server which are replayed with 304 Not Modified
. I would like the browser to cache and use the response without making an If-Modified-Since
call to the server each time.
我发现,即使我指定的Cache-Control最大年龄= 604800
在code,通过WCF发送的响应头为缓存控制无缓存,最大年龄= 604800
。为什么WCF加入了无缓存的一部分,如何从将其加入阻止它?
I noticed that, even though I specify Cache-Control "max-age=604800"
in the code, the response header sent by WCF is Cache-Control no-cache,max-age=604800
. Why is WCF adding the "no-cache" part and how do I stop it from adding it?
推荐答案
尝试设置缓存控制,以公,最大年龄= ...。这可能prevent WCF从应用默认的缓存策略标题。
Try setting Cache-Control to "public,max-age=...". This might prevent WCF from applying the default cache policy header.
另外,还有一些所谓的遥远的将来到期头。对于重长期缓存我使用Expires头代替的Cache-Control:最大年龄= ......并留下的Cache-Control只有公共
Also, there are so called 'far future expire headers'. For heavy long-term caching I use the Expires header instead of Cache-Control:'max-age=...' and leave Cache-Control with just "public".
这篇关于WCF REST JSON服务缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!