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

问题描述 投票:0回答:1

我正在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);
c# asp.net-core blazor-client-side
1个回答
0
投票

这可以通过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();
        }
    }

和Yahoo服务:

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

    }
}

就像那样,您应该使它工作:

enter image description here

让我知道您是否需要我进一步解释其他内容,否则,如果有帮助,请标记为已回答。

© www.soinside.com 2019 - 2024. All rights reserved.