gpt4 book ai didi

c# - 如何在 Blazor WebAssembly 中配置具有不同配置的多个 HttpClient 实例

转载 作者:行者123 更新时间:2023-12-03 13:47:35 25 4
gpt4 key购买 nike

我正在尝试在 Blazor WASM 的 Program.cs 类中配置多个 API url。我没有看到像服务器端那样的 AddHttpClient 扩展。想知道是否有人对此有替代解决方案?

这是我到目前为止所拥有的:

var firstURI = new Uri("https://localhost:44340/");
var secondURI = new Uri("https://localhost:5001/");

void RegisterTypedClient<TClient, TImplementation>(Uri apiBaseUrl)
where TClient : class where TImplementation : class, TClient
{
builder.Services.AddHttpClient<TClient, TImplementation>(client =>
{
client.BaseAddress = apiBaseUrl;
});
}

// HTTP services
RegisterTypedClient<IFirstService, FirstService>(firstURI);
RegisterTypedClient<ISecondService, SecondService>(secondURI);

最佳答案

这可以通过 Blazor 客户端完成。首先,在您的客户端包中,获取以下 nuget 包: Microsoft.Extensions.Http

然后,为这个例子创建两个类(通常你会使用一个接口(interface),但一个类本身应该在这里工作。我将演示使用两个不同的基地址,所以你知道有区别。

   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();
}

接下来,您可以像这样将它们注入(inject)您的前端,并看到它们确实是两个不同的注入(inject)客户端:
@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();

}
}

就像那样,你应该让它工作:

enter image description here

如果您需要我更深入地解释其他任何内容,请告诉我,否则,如果它适合您,请标记为已回答。

关于c# - 如何在 Blazor WebAssembly 中配置具有不同配置的多个 HttpClient 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com