A wrapper for HttpClient that caches to disk. Cached files, over the max specified, are deleted based on the last access times.
See Milestones for release notes.
Headers/Responses respected in caching decisions:
https://nuget.org/packages/Replicant/
There is a default static instance:
var content = await HttpCache.Default.DownloadAsync("https://httpbin.org/status/200");
This caches to {Temp}/Replicant
.
An instance of HttpCache should be long running.
var httpCache = new HttpCache(
cacheDirectory,
// omit for default new HttpClient()
new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
},
// omit for the default of 1000
maxEntries: 10000);
// Dispose when finished
await httpCache.DisposeAsync();
Add HttpCache as a singleton when using dependency injection.
var services = new ServiceCollection();
services.AddSingleton(_ => new HttpCache(cachePath));
using var provider = services.BuildServiceProvider();
var httpCache = provider.GetRequiredService<HttpCache>();
ClassicAssert.NotNull(httpCache);
Using HttpClient with HttpClientFactory.
ServiceCollection services = new();
services.AddHttpClient();
services.AddSingleton(
_ =>
{
var clientFactory = _.GetRequiredService<IHttpClientFactory>();
return new HttpCache(cachePath, () => clientFactory.CreateClient());
});
using var provider = services.BuildServiceProvider();
var httpCache = provider.GetRequiredService<HttpCache>();
ClassicAssert.NotNull(httpCache);
var content = await httpCache.StringAsync("https://httpbin.org/json");
var lines = new List<string>();
await foreach (var line in httpCache.LinesAsync("https://httpbin.org/json"))
{
lines.Add(line);
}
var bytes = await httpCache.BytesAsync("https://httpbin.org/json");
using var stream = await httpCache.StreamAsync("https://httpbin.org/json");
await httpCache.ToFileAsync("https://httpbin.org/json", targetFile);
await httpCache.ToStreamAsync("https://httpbin.org/json", targetStream);
using var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("the content")
};
await httpCache.AddItemAsync(uri, response);
If an error occurs when re-validating a potentially stale item, then the cached item can be used as a fallback.
var content = httpCache.StringAsync(uri, staleIfError: true);
The HttpRequestMessage used can be customized using a callback.
var content = await httpCache.StringAsync(
uri,
modifyRequest: message =>
{
message.Headers.Add("Key1", "Value1");
message.Headers.Add("Key2", "Value2");
});
An instance of the HttpResponseMessage can be created from a cached item:
using var response = await httpCache.ResponseAsync("https://httpbin.org/status/200");
Cyborg designed by Symbolon from The Noun Project.