I had a simple enough requirement, to display the name of the current environment in the title of a Blazor WASM web app.
The Blazor code was simple enough:
appsettings.json: { "Environment": "local" }
Home.razor: @page "/" @inject IConfiguration configuration @{ var title = $"My cool app ({configuration["Environment"]})"; } <PageTitle>@title</PageTitle> <h1>@title</h1>
This displays “My cool app (local)” when debugging locally. I want to change it to “My cool app (dev)”, “My cool app (test)”, and “My cool app (prod)” in each environment it gets deployed to.
A couple of things I tried and failed:
-
- Set a value for “Environment” using the “Environment variables” blade of the Static Web App in the Azure portal – hoping that this would override what’s in the appsettings.json. This doesn’t work, as values set here are only accessible for a managed Azure Function hosted on the static web app and not for front end code running in the browser.
- I tried setting an Environment variable in the AzureStaticWebApp@0 task like
inputs: app_location: 'src' api_location: 'api' output_location: 'public' azure_static_web_apps_api_token: $(deployment_token) env: # Add environment variables here Environment: 'poop'
But that didn’t work.
Eventually I noticed that the Blazor WASM app loads appsettings.json – you can see it in the Browser network tools.
So in my build pipeline I can use the good ol’ Replace Tokens task to replace tokens in my appsettings.json.
Man, that’s a blast from the past, I first used this task about ten years ago!
appsettings.Development.json: { "Environment": "local" } appsettings.json: { "Environment": "#{Environment}#" } build.yml: - task: qetza.replacetokens.replacetokens-task.replacetokens@6 inputs: sources: '**/appsettings.json'
My build pipeline already has a variable called “Environment” so I didn’t have to add that.
I used the same name, i.e. “Environment” in my appsettings.json token and it just worked: