Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

HttpClient BaseAddress is sometimes null in Blazor project

$
0
0

I currently started a new project using Blazor and I am using auto rendermode globally. The structure by default has 2 projects: the server and the client project. I've created a simple login page in the client that uses a HttpClient to call an API from the server to login the user. The BaseAddress is set both in the server and client Program.cs:

Server Program.cs:

builder.Services.AddHttpClient("ServerHttpClient", client =>{    client.BaseAddress = new Uri(builder.Configuration["MainDomain"]!);});

Client Program.cs:

var builder = WebAssemblyHostBuilder.CreateDefault(args);Console.WriteLine($"The BaseAddress is: {builder.HostEnvironment.BaseAddress}");builder.Services.AddScoped<HttpClient>(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });await builder.Build().RunAsync();

And how the request is made:

public partial class Login : ComponentBase{    [Inject]    public HttpClient HttpClient { get; set; } = default!;    async Task LogInAsync()    {        //...some code omitted for brevity        var response = await HttpClient.PostAsync("api/users/signin", content);    }}

The problem is sometimes the HttpClient.BaseAddress is null, sometimes it's populated. When I restart and run the app, sometimes it will throw error with null BaseAddress, sometimes it works with BaseAddress having a value.

If you noticed in the client Program.cs, I've added a log to check the BaseAddress. When no error happens I see that log appear in browser console. But when an error happens, not only is BaseAddress null, the log doesn't even appear. It's like it didn't pass through that line of code. Even if BaseAddress is null, I thought it should have logged at least the string "The BaseAddress is:".

What am I doing wrong?

EDIT:

OK, upon testing it out some more, it seems like it's a timing issue. If I click the login button once it appears, it seems it hasn't run the client code yet (?) and that's why no log appears and BaseAddress is null. I guess this is the prerendered server page (sorry if wrong, I just started reading)? But if I wait for a few seconds, it shows the log and BaseAddress gets value.

If this is indeed the case, how do we usually handle this?

EDIT 2:

I am not sure it is a timing issue because I encountered an instance where the log didn't totally appear even after waiting for a few minutes. But after I refresh, the log shows.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>