c# - System.Net.Http.HttpClient缓存

标签 c# caching xamarin httpclient

有没有办法为 HttpClient 设置缓存? 我想获得 HttpClient 响应(通过 get 方法到达我的端点),但如果客户端设备上没有互联网连接,我想返回此特定调用的最后响应。如果有 Internet 连接,HttpClient 会获取响应(正常行为)并通过此调用的新响应更新缓存。

想在跨平台 Xamarin Forms 项目中设置此行为吗?

最佳答案

您可能会发现其中任何一个有用 Akavache方法:

// Attempt to return an object from the cache. If the item doesn't
// exist or returns an error, call a Func to return the latest
// version of an object and insert the result in the cache.
IObservable<T> GetOrFetchObject<T>(string key, Func<Task<T>> fetchFunc, DateTimeOffset? absoluteExpiration = null);

// Like GetOrFetchObject, but isn't async
IObservable<T> GetOrCreateObject<T>(string key, Func<T> fetchFunc, DateTimeOffset? absoluteExpiration = null);

// Immediately return a cached version of an object if available, but *always*
// also execute fetchFunc to retrieve the latest version of an object.
IObservable<T> GetAndFetchLatest<T>(string key,
    Func<Task<T>> fetchFunc,
    Func<DateTimeOffset, bool> fetchPredicate = null,
    DateTimeOffset? absoluteExpiration = null);

关于c# - System.Net.Http.HttpClient缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805416/

相关文章:

c# - '<Module>' 的类型初始值设定项抛出异常

c# - .NET 6 Web API 应用程序中的错误响应不一致

c# - 在双向关系和 Entity Framework 中保持完整性

javascript - 使用 ServiceWorker 的永久浏览器缓存

xamarin - 我可以使用一个参数同时在模板上设置多个属性吗?

c# - 是否可以将一个颜色资源指向 Xamarin.Forms 中的另一个颜色资源?

string - 如何在 UI 标签中将字符串的一部分设为粗体

c# - 参数化查询(C#、Oracle): How to produce a more readable representation?

c# - 为 Web 服务创建磁盘缓存的最佳方法

kotlin - 如何将@Cacheable 与 Kotlin 挂起功能一起使用