1

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.

Kirk Larkin
  • 60,745
  • 11
  • 150
  • 162
Ali123
  • 683
  • 9
  • 31

1 Answers1

6

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

MindSwipe
  • 4,416
  • 15
  • 30
  • I will test and return back to you , but are you missing some parenthesis '(' this looks like visual basic – Ali123 Sep 18 '18 at 12:22
  • 1
    Or `client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");` – Jimi Sep 18 '18 at 17:08