Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure multiple HttpClient instances with different configurations in Blazor WebAssembly

I'm trying to configure multiple API urls in the Program.cs class in Blazor WASM. I'm not seeing an AddHttpClient extension like in server-side. Was wondering if anyone had an alternate solution for this?

Here's what I have so far:

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);
like image 335
bob82 Avatar asked Feb 17 '20 21:02

bob82


People also ask

What is the difference between Blazor server and Blazor WebAssembly?

Blazor Server apps have direct access to server and network resources where the app is executing. Because Blazor WebAssembly apps execute on a client, they don't have direct access to server and network resources.

What is httpclient in Blazor WebAssembly?

In Blazor we use a class called HttpClient to make http calls to send and receive data from an API. In both the hosting models, that is Blazor WebAssembly and Blazor Server we use this same HttpClient class. There are several approcahes to use this HttpClient class.

How do I make unauthenticated or unauthorized API requests in Blazor WebAssembly?

If the Blazor WebAssembly app ordinarily uses a secure default HttpClient, the app can also make unauthenticated or unauthorized web API requests by configuring a named HttpClient: In Program.cs:

How to create a Blazor page that consumes a typed client?

Let's create a Blazor page that consumes this Typed Client as follows. (Line: 4) Injected the Typed Client into the Blazor page. In this approach HttpRequestMessage object will be used to configure settings like 'domain', 'headers','payload', etc, this object will be used by the HttpClient object to invoke or consume the rest API.

How to send and receive data from an API in Blazor?

In Blazor we use a class called HttpClient to make http calls to send and receive data from an API. In both the hosting models, that is Blazor WebAssembly and Blazor Server we use this same HttpClient class.


1 Answers

This can be done with Blazor Client Side. First, in your client-side package, get the following nuget package: Microsoft.Extensions.Http

Then, create two classes for this example (normally you would use an interface, but a class on its own should work here. I am going to demonstrate two different base addresses being used so you know there is a difference.

   public class GoogleService
    {
        private readonly HttpClient httpClient;

        public GoogleService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }

And the Yahoo Service:

  public class YahooService
    {
        private readonly HttpClient httpClient;

        public YahooService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }

Next, in your Client Program's Program.cs, you can do something like the following:

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

Next, you can inject them into your front end like so, and see that they are indeed two different injected clients:

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

    }
}

And just like that, you should have it working:

enter image description here

Let me know if you need me to explain anything else more in depth, otherwise, mark as answered if it works for you.

like image 138
Kuroiyatsu Avatar answered Oct 06 '22 01:10

Kuroiyatsu