Search code examples
c#xamarin.formshttpclientcache-controlpragma

HTTP Client NoCache Flag Cause Null Reference Exception C#


I added this line to apply no caching in HTTP Client

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.CacheControl.NoCache = true;

When i run the app which was working fine before, i get this exception in the second line:

NullReferenceException: Object reference not set to an instance of an object

I tried this was of applying the NoChache Flag which runs fine but i am not sure if it does what is expected.

HttpClient httpClient = new HttpClient()
{ 
    DefaultRequestHeaders=
    { 
        CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store"),
        Pragma = { NameValueHeaderValue.Parse("no-cache")}
    }
};

Please help me apply the correct way to set the NoCache flag.


Solution

  • It looks like when instantiating a new HttpClient it's CacheControl is set to null. Your solution is a way to set the CacheControl to not cache, but this is a less verbose way of doing it:

    HttpClient httpClient = new HttpClient();
    client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue {NoCache = true};
    

    Edit: Corrected spelling errors