繁体   English   中英

WCF REST JSON 服务缓存

[英]WCF REST JSON service caching

我有一个 WCF web 服务返回 JSON。

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
Stream GetStuff(int arg);

我正在使用这种方法将 object 图转换为 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));
}

我希望将响应缓存在浏览器上,但浏览器仍在生成对服务器If-Modified-Since调用,这些调用通过304 Not Modified重放。 我希望浏览器缓存并使用响应,而无需每次都对服务器进行If-Modified-Since调用。

我注意到,即使我在代码中指定了Cache-Control "max-age=604800" ,但 WCF 发送的响应 header 是Cache-Control no-cache,max-age=604800 为什么 WCF 添加“无缓存”部分,如何阻止它添加?

尝试将 Cache-Control 设置为“public,max-age=...”。 这可能会阻止 WCF 应用默认缓存策略 header。

此外,还有所谓的“远期过期标头”。 对于繁重的长期缓存,我使用 Expires header 而不是 Cache-Control:'max-age=...' 并将 Cache-Control 保留为“public”。

暂无
暂无

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

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