Search code examples
c#asp.net-coreblazorblazor-webassembly

How to do Blazor WASM (Client) initialization from a configuration file of some sort


All,

We have a bunch of WASM components that run on the client. They use HttpClient to post requests to the server. The HTTP Client requires BaseAddress of the server. We need to initialize the BaseAddress in Program.cs that executes on the client from configuration file (ex settings.json). This is required obviously because each client installation will have different server URL. What's the best way to achieve this?

Remember, this initialization code runs on the client, at which point the Server URL must be set.

Maybe is there away to have .net download setings.json (when downloading wasm runtime/dlls) to the client and read it in the Program.cs file logic?


Solution

  • AppSettings.json placed in wwwroot folder of the WASM project

    {
      "ServerBaseURl":  "http://localhost:5000"
    }
    
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");
            builder.RootComponents.Add<HeadOutlet>("head::after");
    
            var baseUrl = builder.Configuration.GetValue<string>("ServerBaseURl") 
                ?? throw new Exception("Unable to read ServerBaseURl..");
    
            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(baseUrl) });
    
            await builder.Build().RunAsync();
        }
    }
    

    enter image description here