5.9禁用缓存与确保成功

在发送 HTTP GET 请求时,服务器可能会缓存该请求的结果以提高性能。为了取消其缓存行为,可以添加 DisableCacheAttribute 特性。

禁用 HTTP 缓存#

在发送 HTTP GET 请求时,服务器可能会缓存该请求的结果以提高性能。为了取消其缓存行为,可以添加 DisableCacheAttribute 特性。

HTTP 声明式请求通过 DisableCacheAttribute 特性来禁用 HTTP 缓存。相应的 HTTP 声明式提取器实现为 DisableCacheDeclarativeExtractor 类型,该类型负责解析 DisableCacheAttribute 特性并构建 HttpRequestBuilder 实例所需的禁用 HTTP 缓存配置。

cs
// 在接口定义上应用,影响所有方法[DisableCache]public interface IHttpService : IHttpDeclarative{    // 在方法上应用    [DisableCache]    [Get("https://furion.net/")]    Task<string> GetStringAsync();    [DisableCache(false)]   // 启用缓存(默认)    [Get("https://furion.net/")]    Task<string> GetStringAsync();}

在添加该特性之后,HTTP 请求将在发送前自动附带以下请求标头,以确保缓存控制:

bash
Cache-Control: must-revalidate, no-cache, no-storePragma: no-cacheIf-None-Match: ""

DisableCacheAttribute 包含以下构造函数和属性:

  • 构造函数

    • new():作用于方法或接口,禁用 HTTP 缓存。
    • new(disabled):作用于方法或接口,设置是否禁用 HTTP 缓存。
  • 属性

    • Disabled:是否禁用(bool 类型),默认值为 true(禁用)。

确保请求成功#

添加 EnsureSuccessStatusCodeAttribute 特性后,当 HTTP 响应的状态码不在 200-299 范围内时(即 IsSuccessStatusCode 属性为 false),将自动抛出异常。

HTTP 声明式请求通过 EnsureSuccessStatusCodeAttribute 特性来确保请求成功。相应的 HTTP 声明式提取器实现为 EnsureSuccessStatusCodeDeclarativeExtractor 类型,该类型负责解析 EnsureSuccessStatusCodeAttribute 特性并构建 HttpRequestBuilder 实例所需的确保请求成功配置。

cs
// 在接口定义上应用,影响所有方法[EnsureSuccessStatusCode]public interface IHttpService : IHttpDeclarative{    // 在方法上应用    [EnsureSuccessStatusCode]    [Get("https://furion.net/")]    Task<string> GetStringAsync();    [EnsureSuccessStatusCode(false)]   // 关闭验证    [Get("https://furion.net/")]    Task<string> GetStringAsync();}

EnsureSuccessStatusCodeAttribute 包含以下构造函数和属性:

  • 构造函数

    • new():作用于方法或接口,确保请求成功。
    • new(enabled):作用于方法或接口,设置是否确保请求成功。
  • 属性

    • Enabled:是否启用(bool 类型),默认值为 true(启用)。