Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are (string[] args) passed to Program.Main in a Blazor WebAssembly app?

The Program.Main method in a Blazor WASM app has string[] args parameter. Is it possible for the ASP.NET Core host site to pass arguments into these? I need to be able to read a value from the server before the app has been built.

like image 284
Peter Morris Avatar asked Mar 03 '23 16:03

Peter Morris


2 Answers

Program.Main is invoked by blazor.webassembly.js here:

invokeEntrypoint(assemblyName, null);

which hits a dotnet static method which then turns the null into an empty array.

So no, it's not possible to pass arguments to it right now because you only ever get an empty array.

like image 106
Nick Darvey Avatar answered Apr 05 '23 23:04

Nick Darvey


There is no default way to pass these parameters in, because indeed they are hardcoded to be null in blazor.webassembly.js. It is however possible to provide them via javascript.

In your index page, include the following:

<!-- Put this script block above the one that loads blazor.webassembly.js -->
<script>
    window.startupParams = function() { return ['first', 'second', 'third']; };
</script>

In your Program.cs:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    var js = (IJSInProcessRuntime)builder.Services.BuildServiceProvider().GetRequiredService<IJSRuntime>();
    var startupParams = js.Invoke<string[]>("startupParams");

    // ... etc ...
}

As found in this github answer.

We serve the index page from asp.net core, as an index.cshtml page. And have logic on the server-side to populate the array in the script with the needed parameters.

like image 45
Bjorn De Rijcke Avatar answered Apr 06 '23 01:04

Bjorn De Rijcke