8.8Sending relative-address (internal) requests
In Web applications such as ASP.NET or Blazor, relative addresses are typically used when sending internal HTTP requests. However, since the host address and port cannot be obtained before the project starts, BaseAddress cannot be configured directly through services.AddHttpClient(). In this case, you can configure the FallbackBaseAddress of HttpRemoteOptions instead.
ASP.NETapplications
services.AddHttpRemote() .ConfigureOptions((options, serviceProvider) => { var serverAddressesFeature = serviceProvider.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!; options.FallbackBaseAddress = new Uri(serverAddressesFeature.Addresses.FirstOrDefault()); });Blazor WebAssemblyapplications
services.AddHttpRemote() .ConfigureOptions((options, serviceProvider) => { var navigation = serviceProvider.GetRequiredService<NavigationManager>(); options.FallbackBaseAddress = new Uri(navigation.BaseUri); });With the above configuration, you can send relative-address (internal) requests, as shown in the following example:
var content = await httpRemoteService.GetAsStringAsync("/user/1"); // Relative address (internal)When sending a relative-address request, the system automatically obtains the host address and port used when the Web host started and concatenates them. For example, the final request address sent may be: https://localhost:5001/user/1. This approach simplifies the configuration of internal requests and ensures the host address and port are obtained dynamically at project startup, thereby avoiding maintenance problems caused by hardcoding.