What's the correct way to set Blazor Webassembly environment?
Asked Answered
S

2

12

My goal is to be able to change the environment name from configuration file. If the server is configured for X, then the client should also use X environment.

You know, in ASP.NET we can use launchSettings.json to configure IIS server to Development, and the "real" server which is published to Production. The WASM client should see the same configuration. I would like to configure the environment only here to reduce the resik of forgetting something when publishing the server.

There are multiple articles describing Blazor environments, but I'm confused setting it up correctly.

To get the environment saw by the client, I added this line to the Client/Program.cs file:

Console.WriteLine("Using environment " + builder.HostEnvironment.Environment);

Experiemets:

  • If I change the Server/launchSettings.json/profiles/IIS Express/environmentVariables/ASPNETCORE_ENVIRONMENT from Development to Production, the website simply won't load (returns 404).

  • In some other cases, ASPNETCORE_ENVIRONMENT is just ignored / not accessible by the client.

  • When running an app locally, the environment defaults to Development. When the app is published, the environment defaults to Production.

    That's true sometimes for me, but not always. Some cases the environment is Production even if I run locally.

  • Blazor.start({ environment: "Staging" }); described in this article has no effect. Also that takes a string, how could I pass the server side config variable's value?

  • Using web.config, I can always overwrite the environment name. There's two problems:

    1. Why maintain another configuration file? There's already launchSettings.json, and the server will depend on that file. As far as I know, I can't reference other settings from the web.config file.
    2. It's really not the blazor-environment header which controls the environment name. Why?
      • Remove web.config

      • In Server/Startup.cs, add:

        app.Use(async (context, next) =>
        {
            context.Response.Headers.Add("blazor-environment", env.EnvironmentName);
            await next.Invoke();
        });
        
      • In Chrome DevTools, I can see the value of the header is indeed Development. But the client prints Production.

      • If the header is ignored, why would I set it in web.config? It it's set, but the clinet WASM project doesn't read the header, how else it knowns the name? Is the referenced Blazor WASM JavaScript file changed, the environment name is compiled into that?

  • There is also Client/launchSettings.json generated, which seem to be completely ignored.

  • There are at least 10 ways described to get the environment name. Some use appsettings.json (which is separately download, or IWebAssemblyHostEnvironment, or IConfiguration, or Razor component ect. All I want is to read the global environment name in C# code parts.

I guess this chaos comes from the fact Blazor was changed in the recent years. I'm a bit lost. Which one should I use? Which should always work? Can I get rid of the need to change both web.config and launchSettings.json?

Saied answered 30/5, 2021 at 12:17 Comment(3)
Maybe you can refer to the link.Alcheringa
Did you ever figure out how to the environment to something other than "Development"Prine
Great post. Perhaps this should be raised as a GitHub issue for the project?Hardden
A
6

If your wasm is hosted by an asp.net core app, the call to

app.UseBlazorFrameworkFiles();

should add the headers required automatically. You can check this by looking at the headers passed back in a network monitor for the blazor.boot.json file, which is the request that blazor uses to read the blazor-environment header from.

Note that in the sample where you manually added that header, if you didn't add it before the 'AddStaticFiles', that header probably would have been added to your index page, but NOT the blazor.boot.json file, so it would have had no effect.

One other thing to take note of is that the call to app.UseBlazorFrameworkFiles() MUST go before app.UseStaticFiles(). That one tripped me up, hopefully that helps anyone who comes in here searching for an answer :)

ref: code where blazor wasm reads header: https://github.com/dotnet/aspnetcore/blob/5fed81205944c528cbf7bb3a4ce369ca37bd3676/src/Components/Web.JS/src/Platform/BootConfig.ts#L29

Affairs answered 29/6, 2022 at 4:0 Comment(2)
I'm not really clear on what this function does and the documentation is incomplete?Labradorite
Thank you. For me, app.UseBlazorFrameworkFiles() was after app.UseStaticFiles(). When I switched them, everything worked normally.Pancratium
I
-5

I'm using Blazor Server and not Blazor Web Assembly, but I'm thinking you can do what I do and just set the environment in the ASPNETCORE_ENVIRONMENT variable. When debugging in Visual Studio, set the variable in the launchSettings.json file (note if you have multiple profiles such as IIS Express and YourProject, the variable should exist for each profile (best to keep the value for the variable the same)). When running the app on a server, the ASPNETCORE_ENVIRONMENT variable should exist as an environment variable on the server (VM or physical on-prem etc) or for Azure Web Site (aka Azure App Service) as a variable under Settings->Configuration. Note for environment variables you typically have to log out the runtime user and restart the service before the new value will be read.

If you have code such as env.IsDevelopment(), env.IsStaging(), or env.IsProduction, you will need to use the standard environment names (Development, Staging, and Production).

For Blazor Server, inside Program.cs CreateHostBuilder method where you call Host.CreateDefaultBuilder(args).CongigureWebHostDefaults(webHostBuilder =>

you can read the environment variable this way:

ConfigurationBuilder = new ConfigurationBuilder()
.AddEnvironmentVariables("ASPNETCORE_");

const string aspnetCoreEnv = "ASPNETCORE_ENVIRONMENT";
var environmentName = Environment.GetEnvironmentVariable(aspnetCoreEnv);

Now add the appropriate appsettings file containing the environment name:

ConfigurationBuilder.AddJsonFile($"appsettings.{EnvironmentName}.json", true, true);

var configuration = ConfigurationBuilder.Build();
webHostBuilder.UseConfiguration(configuration);
var hostBuilderEnvironmentSetting = webHostBuilder.GetSetting(WebHostDefaults.EnvironmentKey);
if (string.IsNullOrEmpty(hostBuilderEnvironmentSetting))
    webHostBuilder.UseSetting(WebHostDefaults.EnvironmentKey, EnvironmentName);

If you are using Startup.cs, then you can use constructor injection so you can access the environment within Startup:

public Startup(IConfiguration configuration, IWebHostEnvironment hostingEnvironment)

If Blazor Web Assembly configures differently, maybe you can still achieve the equivalent logic to make it load the appsettings that match the environment.

With this approach, I have not encountered issues where the app does not identify the environment properly. I don't have a web.config file so haven't needed to maintain values there. The only "won't load" issue I have hit was in Azure where my publish config specified a "Microsoft Identity Platform" which references an Azure App Registration and that app registration didn't have under Redirect URIs a Web Platform with URI for my environment-specific app service.

Instable answered 5/10, 2021 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.