How to override blazor client configuration with environment variables?

Viewed 1284

I have working web client, it uses "wwwroot/appsettings.json" file for its configuration.

Now I would like to override just single settings using environment variable for it (as an example, in reality there will be many, arbitrary, overrides). Is there ready to use mechanism, similar to ASP.NET Core server (all it takes is calling extension method and combining json, env. variables)?

I am not asking about multiple .json files and switching between them depending on ENVIRONMENT variable, it is completely different scenario.

So far I didn't find anything even close, so thinking about DIY approach I see an ugly path -- moving client configuration file into hosting server, adding main node in client .json file like "client", using environment variables with prefix "client", merging those data using ASP.NET server mechanism, dumping it back to file for the client usage. And hoping it will work :-).

1 Answers

So I followed DIY path :-) If anyone like it here are the steps:

  • create 3 files with empty JSON at web client wwwroot -- appsettings.json, appsettings.Development.json and Production version as well

  • put your entire web client config in appsettings.json at hosting server at "CLIENT" node for example

  • in your server Startup constructor create configuration as usual, but then fetch entire "CLIENT" section and "jsonize" it back (see: https://stackoverflow.com/a/62533775/6734314) -- convert it to string and write to $"wwwroot/appsettings.{env.EnvironmentName}.json" (where env is IWebHostEnvironment)

And that's it -- I tested it in Development mode and in Production. The only drawbacks I see are:

  • it looks weird :-)
  • when executed using VS the written file is put not relative to binary file, but relative to project -- so when you are done you have to delete newly created file (otherwise on the next run VS will complain about conflict between two static files)

You override the settings using env. variables at server side using "CLIENT" prefix, and the rest is as usual.

For the record, I am not saying this is perfect, but I didn't look for anything more than I asked in my question. What I would like to do however is to reduce the number of steps, or even better to use some already existing mechanism. I will be grateful for the improvements/tips within those areas.

Related