![]() |
VOOZH | about |
dotnet add package HttpClient.Caching --version 1.6.6
NuGet\Install-Package HttpClient.Caching -Version 1.6.6
<PackageReference Include="HttpClient.Caching" Version="1.6.6" />
<PackageVersion Include="HttpClient.Caching" Version="1.6.6" />Directory.Packages.props
<PackageReference Include="HttpClient.Caching" />Project file
paket add HttpClient.Caching --version 1.6.6
#r "nuget: HttpClient.Caching, 1.6.6"
#:package HttpClient.Caching@1.6.6
#addin nuget:?package=HttpClient.Caching&version=1.6.6Install as a Cake Addin
#tool nuget:?package=HttpClient.Caching&version=1.6.6Install as a Cake Tool
👁 Version
👁 Downloads
👁 Buy Me a Coffee
This library is available on NuGet: https://www.nuget.org/packages/HttpClient.Caching/ Use the following command to install HttpClient.Caching using NuGet package manager console:
PM> Install-Package HttpClient.Caching
You can use this library in any .Net project which is compatible to .Net Framework 4.5+ and .Net Standard 1.2+ (e.g. Xamarin Android, iOS, Universal Windows Platform, etc.)
HTTP Caching affects both involved communication peers, the client and the server. On the server-side, caching is appropriate for improving throughput (scalability). HTTP caching doesn't make a single HTTP call faster but it can lead to better response performance in high-load scenarios. On the client-side, caching is used to avoid unnecessarily repetitiv HTTP calls. This leads to less waiting time on the client-side since cache reads have naturally a much better response performance than HTTP calls over relatively slow network links.
Declare IMemoryCache in your API service, either by creating an instance manually or by injecting IMemoryCache into your API service class.
private readonly IMemoryCache memoryCache = new MemoryCache();
Following example show how IMemoryCache can be used to store an HTTP GET result in memory for a given time span (cacheExpirection):
public async Task<TResult> GetAsync<TResult>(string uri, TimeSpan? cacheExpiration = null)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
TResult result;
var caching = cacheExpiration.HasValue;
if (caching && this.memoryCache.TryGetValue(uri, out result))
{
stopwatch.Stop();
this.tracer.Debug($"{nameof(this.GetAsync)} for Uri '{uri}' finished in {stopwatch.Elapsed.ToSecondsString()} (caching=true)");
return result;
}
var httpResponseMessage = await this.HandleRequest(() => this.httpClient.GetAsync(uri));
var jsonResponse = await this.HandleResponse(httpResponseMessage);
result = await Task.Run(() => JsonConvert.DeserializeObject<TResult>(jsonResponse, this.serializerSettings));
if (caching)
{
this.memoryCache.Set(uri, result, cacheExpiration.Value);
}
else
{
this.memoryCache.Remove(uri);
}
stopwatch.Stop();
this.tracer.Debug($"{nameof(this.GetAsync)} for Uri '{uri}' finished in {stopwatch.Elapsed.ToSecondsString()}");
return result;
}
HttpClient allows to inject a custom http handler. In the follwing example, we inject an HttpClientHandler which is nested into an InMemoryCacheHandler where the InMemoryCacheHandler is responsible for maintaining and reading the cache.
static void Main(string[] args)
{
const string url = "http://worldtimeapi.org/api/timezone/Europe/Zurich";
var httpClientHandler = new HttpClientHandler();
var cacheExpirationPerHttpResponseCode = CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5));
var handler = new InMemoryCacheHandler(httpClientHandler, cacheExpirationPerHttpResponseCode);
using (var client = new HttpClient(handler))
{
// HttpClient calls the same API endpoint five times:
// - The first attempt is called against the real API endpoint since no cache is available
// - Attempts 2 to 5 can be read from cache
for (var i = 1; i <= 5; i++)
{
Console.Write($"Attempt {i}: HTTP GET {url}...");
var stopwatch = Stopwatch.StartNew();
var result = client.GetAsync(url).GetAwaiter().GetResult();
// Do something useful with the returned content...
var content = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine($" completed in {stopwatch.ElapsedMilliseconds}ms");
// Artificial wait time...
Thread.Sleep(1000);
}
}
Console.WriteLine();
StatsResult stats = handler.StatsProvider.GetStatistics();
Console.WriteLine($"TotalRequests: {stats.Total.TotalRequests}");
Console.WriteLine($"-> CacheHit: {stats.Total.CacheHit}");
Console.WriteLine($"-> CacheMiss: {stats.Total.CacheMiss}");
Console.ReadKey();
}
Console output:
Attempt 1: HTTP GET http://worldtimeapi.org/api/timezone/Europe/Zurich... completed in 625ms
Attempt 2: HTTP GET http://worldtimeapi.org/api/timezone/Europe/Zurich... completed in 48ms
Attempt 3: HTTP GET http://worldtimeapi.org/api/timezone/Europe/Zurich... completed in 1ms
Attempt 4: HTTP GET http://worldtimeapi.org/api/timezone/Europe/Zurich... completed in 1ms
Attempt 5: HTTP GET http://worldtimeapi.org/api/timezone/Europe/Zurich... completed in 1ms
TotalRequests: 5
-> CacheHit: 4
-> CacheMiss: 1
By default, requests will be cached by using a key which is composed with http method and url (only HEAD and GET http methods are supported). If this default behavior isn't enough you can implement your own ICacheKeyProvider wich provides cache key starting from HttpRequestMessage.
The following example show how use a cache provider of type MethodUriHeadersCacheKeysProvider. This cache key provider is already implemented and evaluates http method, specified headers and url to compose a cache key. with InMemoryCacheHandler.
static void Main(string[] args)
{
const string url = "http://worldtimeapi.org/api/timezone/Europe/Zurich";
var httpClientHandler = new HttpClientHandler();
var cacheExpirationPerHttpResponseCode = CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5));
// this is a CacheKeyProvider which evaluates http method, specified headers and url to compose a key
var cacheKeyProvider = new MethodUriHeadersCacheKeysProvider(new string[] { "FIRST-HEADER", "SECOND-HEADER" });
var handler = new InMemoryCacheHandler(
innerHandler: httpClientHandler,
cacheExpirationPerHttpResponseCode: cacheExpirationPerHttpResponseCode,
cacheKeysProvider: cacheKeyProvider
);
using (var client = new HttpClient(handler))
{
// HttpClient calls the same API endpoint five times:
// - The first attempt is called against the real API endpoint since no cache is available
// - Attempts 2 to 5 can be read from cache
for (var i = 1; i <= 5; i++)
{
Console.Write($"Attempt {i}: HTTP GET {url}...");
var stopwatch = Stopwatch.StartNew();
var result = client.GetAsync(url).GetAwaiter().GetResult();
// Do something useful with the returned content...
var content = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine($" completed in {stopwatch.ElapsedMilliseconds}ms");
// Artificial wait time...
Thread.Sleep(1000);
}
}
Console.WriteLine();
StatsResult stats = handler.StatsProvider.GetStatistics();
Console.WriteLine($"TotalRequests: {stats.Total.TotalRequests}");
Console.WriteLine($"-> CacheHit: {stats.Total.CacheHit}");
Console.WriteLine($"-> CacheMiss: {stats.Total.CacheMiss}");
Console.ReadKey();
}
How-to: HTTP Caching for RESTful & Hypermedia APIs
This project is Copyright © 2022 Thomas Galliker. Free for non-commercial use. For commercial use please contact the author.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 is compatible. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 is compatible. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp1.0 netcoreapp1.0 was computed. netcoreapp1.1 netcoreapp1.1 was computed. netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard1.2 netstandard1.2 is compatible. netstandard1.3 netstandard1.3 was computed. netstandard1.4 netstandard1.4 was computed. netstandard1.5 netstandard1.5 was computed. netstandard1.6 netstandard1.6 was computed. netstandard2.0 netstandard2.0 is compatible. netstandard2.1 netstandard2.1 is compatible. |
| .NET Framework | net451 net451 was computed. net452 net452 was computed. net46 net46 was computed. net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 is compatible. net481 net481 was computed. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen30 tizen30 was computed. tizen40 tizen40 was computed. tizen60 tizen60 was computed. |
| Universal Windows Platform | uap uap was computed. uap10.0 uap10.0 was computed. |
| Windows Phone | wpa81 wpa81 was computed. |
| Windows Store | netcore451 netcore451 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 3 NuGet packages that depend on HttpClient.Caching:
| Package | Downloads |
|---|---|
|
Terradue.Stars
Stars is a set of services for working with Spatio Temporal Catalog such as STAC but not only |
|
|
Neutron.Web.ClienteAPI
Biblioteca para utilizar a API do Software Neutron. |
|
|
GarageGroup.Infra.Http.Cache
Package Description |
Showing the top 2 popular GitHub repositories that depend on HttpClient.Caching:
| Repository | Stars |
|---|---|
|
ThePornDatabase/Jellyfin.Plugin.ThePornDB
Jellyfin/Emby Metadata Provider
|
|
|
DirtyRacer1337/Jellyfin.Plugin.PhoenixAdult
Jellyfin/Emby Metadata Provider for videos from multiple adult sites
|
| Version | Downloads | Last Updated |
|---|---|---|
| 2.0.19-pre | 106 | 6/3/2026 |
| 2.0.17-pre | 101 | 5/28/2026 |
| 2.0.15-pre | 128 | 5/16/2026 |
| 2.0.14-pre | 139 | 5/11/2026 |
| 2.0.12-pre | 141 | 4/21/2026 |
| 2.0.7-pre | 114 | 4/6/2026 |
| 2.0.6-pre | 103 | 4/6/2026 |
| 1.6.6 | 8,303 | 5/26/2025 |
| 1.6.0-pre | 252 | 2/24/2025 |
| 1.5.13-pre | 209 | 2/24/2025 |
| 1.5.12-pre | 672 | 10/24/2024 |
| 1.5.8-pre | 702 | 10/1/2024 |
| 1.5.5-pre | 216 | 9/1/2024 |
| 1.5.4-pre | 200 | 8/1/2024 |
| 1.5.3-pre | 260 | 7/7/2024 |
| 1.5.2-pre | 212 | 7/7/2024 |
| 1.5.1-pre | 229 | 6/26/2024 |
| 1.4.10-pre | 210 | 7/1/2024 |
| 1.4.8-pre | 199 | 6/1/2024 |
| 1.4.7-pre | 259 | 5/1/2024 |
1.3
- Add ICacheKeysProvider which allows to specify custom cache keys
1.0
- Initial release