Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles. Follow galratner on Twitter
How to prevent the browser from caching WCF JSON responses

When calling an AJAX enabled WCF service the default browser behavior is to cache the output JS file. It’s a great performance enhancer, however, when you need to stop it and reload a fresh response you can simply set the cache HTTP headers in the following way.
In your service, include System.Web

using System.Web;

 


Then set the headers within the WCF function call.

 

    [WebGet]

    [OperationContract]

    public StatusContract[] GetStatus(int startRecordID, int count)

    {

        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        HttpContext.Current.Response.Cache.SetNoStore();

 

       //Do somthing

        return statuss;

    }

 

This will generate a new function call without caching the result. Alternatively, you can also use:

 

 

WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");


Posted 7 Sep 2009 5:28 AM by Gal Ratner

Comments

Scott wrote re: How to prevent the browser from caching WCF JSON responses
on 4 Oct 2009 9:15 AM

Works great thanks!

Powered by Community Server (Non-Commercial Edition), by Telligent Systems