5.26Setting the Request Base Address
When you need to integrate with multiple third-party APIs, you usually register and configure the BaseAddress of multiple HttpClient instances globally. For example:
// Configure the base address of the default clientservices.AddHttpClient(string.Empty, client =>{ client.BaseAddress = new Uri("https://furion.net/");});// Configure the base address of the GitHub clientservices.AddHttpClient("github", client =>{ client.BaseAddress = new Uri("https://github.com/");});You can then specify the client to use via the [HttpClientName(client name)] attribute.
In addition to global configuration, the framework also supports setting the base address locally in Declarative Requests, allowing it to be specified dynamically when building the request.
HTTP Declarative Requests set the request base address through the BaseAddressAttribute attribute. The corresponding HTTP declarative extractor is implemented as the BaseAddressDeclarativeExtractor type, which is responsible for parsing the BaseAddressAttribute attribute and building the request base address configuration required by an HttpRequestBuilder instance.
// Apply at the interface level to affect all methods[BaseAddress("https://furion.net")]public interface IHttpService : IHttpDeclarative{ [Get("/api/test")] Task<string> GetStringAsync(); // Apply at the method level [BaseAddress("https://baiqian.com")] [Get("/api/test/2")] Task<string> GetStringAsync(); // Can be used as a prefix [BaseAddress("/furion")] [Get("/api/test/2")] Task<string> GetStringAsync();}Once enabled, the request base address is automatically set when sending HTTP remote requests.
Processing Logic:
- If the request address is an absolute address, that address is used directly to send the request.
- If the request address is a relative address:
- When no local
BaseAddressis set, it is combined with theBaseAddressof the globalHttpClientinstance to form the final request address. - When a local
BaseAddressis set:- If the local
BaseAddressis a relative address, it is first prepended to the request address and then combined with the globalBaseAddress. - If the local
BaseAddressis an absolute address, that absolute address is directly combined with the request address to form the final request address (the globalBaseAddressis ignored in this case).
- If the local
- When no local
BaseAddressAttribute includes the following constructors and properties:
-
Constructors:
new(baseAddress): Applies to methods or interfaces, setting the request base address.
-
Properties:
BaseAddress: The request base address (typestring).