C# WCF REST JSON服务缓存

C# WCF REST JSON服务缓存,c#,.net,wcf,json,http,C#,.net,Wcf,Json,Http,我有一个返回JSON的WCF web服务 [OperationContract] [WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] Stream GetStuff(int arg); 我使用这个方法将对象图转换为JSON: private static Stream ToJson(object obj) { JavaScriptSerializer seriali

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

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
Stream GetStuff(int arg);
我使用这个方法将对象图转换为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));
}
我希望将响应缓存在浏览器上,但如果修改,浏览器仍会生成
,因为
调用服务器,并使用
304 Not Modified
重播。我希望浏览器缓存并使用响应,而不必在每次调用服务器时修改


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

尝试将缓存控制设置为“公共,最大年龄=…”。这可能会阻止WCF应用默认缓存策略头


此外,还有所谓的“远未来过期标头”。对于大量的长期缓存,我使用Expires头而不是缓存控制:“max-age=…”并将缓存控制保留为“public”。

谢谢,这解决了我的问题:HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddDays(14));HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);我不确定HttpContext.Current是否在WCF web服务中可用。只有在aspNet兼容模式下运行时才可用。