开发者

WCF REST JSON service caching

开发者 https://www.devze.com 2023-03-11 16:38 出处:网络
I have a WCF web service returning JSON. [OperationContract] [WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]

I have a WCF web service returning JSON.

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

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; c开发者_开发技巧harset=utf-8";
        outgoingResponse.Headers.Add(HttpResponseHeader.CacheControl, "max-age=604800"); // one week
        outgoingResponse.LastModified = DateTime.Now;
    }

    return new MemoryStream(Encoding.UTF8.GetBytes(json));
}

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.

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?


Try setting Cache-Control to "public,max-age=...". This might prevent WCF from applying the default cache policy header.

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".

0

精彩评论

暂无评论...
验证码 换一张
取 消