How to disable cache for asynchronous HTTPWebRequest for Windows Phone application?
I am developing a mobile app using Rest API. I'm using Asynchronous calls as GetResponse method is not supported in Windows Phone 8 development.
When I launch the application, it fetches the correct data using GET method. I have implemented a 60 second refresh interval. When the refresh triggers, the JSON output that I receive is not the new one but the one fetched initially. Basically it is not refreshing. I went through some of the blogs here and found that it is an issue with caching. I need help with disabling this cache. Also, I checked and found that HttpRequestCachePolicy cannot be used as System.Net.Cache doesnt exist in the framework (I am new to development so please correct me if I'm wrong here)
Below is the code that I'm using.
string AuthServiceUri = "http://" + Authentication.ipAddress + "/api/alerts/open"; HttpWebRequest alerts_request = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest; alerts_request.Accept = "application/json"; alerts_request.Method = "GET"; alerts_request.Headers["AuthToken"] = Authentication.authToken; alerts_request.BeginGetResponse(new AsyncCallback(AlertsGetResponsetStreamCallback), alerts_request);
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult); response.Headers["Cache-Control"] = "no-cache"; string responseString = ""; Stream streamResponse = response.GetResponseStream(); StreamReader reader = new StreamReader(streamResponse); responseString = reader.ReadToEnd(); streamResponse.Close(); reader.Close(); response.Close(); string result = responseString;
The code works just fine fetching the results. Just that I'm having trouble clearing the cache. Am I implementing the "no-cache" correctly here by adding it to the header? Or am I missing something? Should it be added to the header as well? Be my savior!!
The quickest workaround is probably to modify the uri with every call. This will bypass caching. Just append a parameter like "?dummy=345" to your uri and change the parameter value (345) with every call. This looks like a new uri to the caching mechanism and it will retrieve the content.