这可以通过 Blazor 客户端完成。首先,在您的客户端包中,获取以下 nuget 包:Microsoft.Extensions.Http
然后,为此示例创建两个类(通常您会使用一个接口,但在这里应该单独使用一个类。我将演示使用两个不同的基地址,以便您知道存在差异。
public class GoogleService
{
private readonly HttpClient httpClient;
public GoogleService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public string GetBaseUrl()
{
return httpClient.BaseAddress.ToString();
}
}
还有雅虎服务:
public class YahooService
{
private readonly HttpClient httpClient;
public YahooService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public string GetBaseUrl()
{
return httpClient.BaseAddress.ToString();
}
}
接下来,在您的客户程序的 Program.cs 中,您可以执行以下操作:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddHttpClient<GoogleService>(client =>
{
client.BaseAddress = new Uri("https://google.com/");
});
builder.Services.AddHttpClient<YahooService>(client =>
{
client.BaseAddress = new Uri("https://yahoo.com/");
});
await builder.Build().RunAsync();
}
接下来,您可以像这样将它们注入您的前端,并看到它们确实是两个不同的注入客户端:
@page "/"
@inject BlazorHttpClientTest.Client.Clients.GoogleService googleService;
@inject BlazorHttpClientTest.Client.Clients.YahooService yahooService;
<h1>Hello, world!</h1>
<label>Google Address:</label><label>@googleAddress</label>
<label>Yahoo Address:</label><label>@yahooAddress</label>
@code{
string googleAddress;
string yahooAddress;
protected override void OnInitialized()
{
base.OnInitialized();
googleAddress = googleService.GetBaseUrl();
yahooAddress = yahooService.GetBaseUrl();
}
}
就这样,你应该让它工作:
如果您需要我更深入地解释其他任何内容,请告诉我,否则,如果对您有用,请标记为已回答。