How to get the server url in blazor webassembly app?

Viewed 33

I have a .NET Web Api Server and a Blazor Webassembly Client.

My problem is, that I don't know where to set the server base url on the client side. If I would deploy it to a docker container, my guess would be, that it should come from an environment variable.

The only solution that I found is through:

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

At least in my local dev environment this obviously routes me always to the frontend base url.

So where do I need to set the backend url or how can I read out the env variable if it is deployed to a docker container so I can use it in signalR or REST-Calls?

1 Answers

In Wasm you can access the 'HostEnvironment' with

if (builder.HostEnvironment.IsDevelopment())
{
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new 
    Uri(builder.HostEnvironment.BaseAddress) });
}

if (builder.HostEnvironment.IsProduction())
{
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("SomeotherAddress") });
}

await builder.Build().RunAsync();

you'll need to set the env for example : dotnet run --environment Production doc's

Related