15

In my .NET Standard project I'm using System.Net.Http.HttpClient. How can I disable all caching (request caching especially) in HttpClient?

If server sends responses with no cache header problem solves. But I want to make this on client side. I want to completely disable all caching.

Thanks.

Edit: It looks like I could use WebRequestHandler but this does not exist in .NET standard. I can only use HttpClientHandler but HttpClientHandler doesn't have any option about caching.

2 Answers 2

42

You can use CacheControlHeaderValue in HttpClient

using System.Net.Http.Headers;

httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
{
  NoCache = true
}

For more information you can look https://learn.microsoft.com/en-us/dotnet/api/system.net.http.headers.cachecontrolheadervalue

Sign up to request clarification or add additional context in comments.

Comments

4

I tried everything, this one worked for me. Just in case some is not able to make the accepted answer work:

var uri = new Uri("http://localhost:8080/v?time=" + DateTime.Now);
var client = new HttpClient();
var response = await client.GetAsync(uri);

2 Comments

I'm confused to what this solution is doing. Are you recommending newing up an HttpClient for each request? If that's the case, be aware that HttpClient is designed to be shared throughout the application. Creating a new one on each request is likely to run you out of TCP sockets. (If you're using ASP.Net or modern .Net, you'll want to use services.AddHttpClient(). If using .Net's service collection isn't an option, then HttpClientFactory will also handle pooling HttpClients.)
@Josh - I think the idea is to use a unique query argument to bust the cache lookup. You are correct though in that new'ing up a HttpClient for each request is <strike>generally</strike> a bad idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.