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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With