5.2请求地址与同步异步

在 HttpMethodAttribute 及其派生特性的构造函数中,您可以配置请求的地址。以下展示了如何在 IHttpService 接口中利用这些特性来定义不同的请求地址:

定义请求地址#

HttpMethodAttribute 及其派生特性的构造函数中,您可以配置请求的地址。以下展示了如何在 IHttpService 接口中利用这些特性来定义不同的请求地址:

cs
public interface IHttpService : IHttpDeclarative{    // 使用完整 URL 地址    [Get("https://furion.net/")]    Task<string> GetFullUrlMethodAsync();    // 使用相对地址(不含前导斜杠)    [Get("api/get/user")]    Task<string> GetRelativeUrlMethod1Async();    // 使用相对地址(含前导斜杠)    [Get("/api/get/user")]    Task<string> GetRelativeUrlMethod2Async();    // 请求地址为空字符串,实际请求为 BaseAddress    [Get("")]    Task<string> GetEmptyUrlMethodAsync();    // 请求地址为 null,实际请求为 BaseAddress    [Get(null)]    Task<string> GetNullUrlMethodAsync();    // 请求地址为 null,实际请求为 BaseAddress    [Get]    Task<string> GetNullUrlMethodAsync();}
  • 当提供的请求地址为完整 URL 时,它将直接作为最终的请求地址。
  • 若请求地址为相对地址(无论是否包含前导斜杠 /),框架将尝试将其与 HttpClient 配置的 BaseAddress 合并,以生成最终的请求地址。例如:
cs
services.AddHttpClient(string.Empty, client =>{    client.BaseAddress = new Uri("https://furion.net/");});

在上述配置中,若请求地址为 "api/get/user""/api/get/user",则最终的请求地址将为 "https://furion.net/api/get/user"

  • 若请求地址为空字符串或 null,则 HttpClient 配置的 BaseAddress 将直接作为最终的请求地址。这意味着,如果 BaseAddress"https://furion.net/",则最终请求地址也将是 "https://furion.net/"

同步与异步方法#

IHttpService 的声明式请求接口方法定义中,我们既提供了异步方法的实现,也支持同步方法的定义。例如:

cs
public interface IHttpService : IHttpDeclarative{    // 异步请求方法    [Get("https://furion.net/")]    Task<string> GetMethodAsync();    // 同步请求方法    [Get("https://furion.net/")]    string GetMethod();}