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:
- 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.
- 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
, orIConfiguration
, 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?