Is it possible to pass environment variables from the host to a hosted blazor wasm app?

Viewed 891

I'm hosting a blazor wasm app from an aspcore host like this

public void Configure(IApplicationBuilder app)
{
    // ...
    app.UseBlazorFrameworkFiles();
    // ...
}

Now I want to deploy my app with docker. And I want to control the address for the backend of the blazor app from an environment variable.

So I've setup wwwroot/appsettings.json in my blazor project which works just as expected. Values get read at runtime. But they won't get overriden by the hosts environment variables.

Is there a way to pass a value down the line? I could read the environment variable in the host and pass it somehow else down. But the client needs to read it from the appsettings.json resource.

I probably could do it w/o the appsettings.json file and create a custom endpoint which returns a string. But I don't like that approach.

1 Answers

Instead of setting the Fallback path to the index.html file you can create a new Razor Page in the Server project. In this page you render the App component of the client project. This blog explains the process in great detail. If you choose to prerender or not the process is the same. https://andrewlock.net/enabling-prerendering-for-blazor-webassembly-apps/. If you are not ok with prerendering the Blazor WebAssembly app you can just set the render-mode to WebAssembly.

<component type="typeof({NameOfClientProject}.App)" render-mode="WebAssembly" />

You then need to define a Parameter in the App razor Component from the Child project.

[Parameter]
public Hashtable EnvironmentInfo { get; set; }

And then we extend the previous snippet, the _Host.cshtml page, to the following so that we pass the EnvironmentVariables:

<component param-EnvironmnentInfo='@Environment.GetEnvironmentVariables()' type="typeof(BlazorWAEnvironment.Client.App)" render-mode="WebAssembly" />
Related