Is there a way to get AddOptionsWithValidateOnStart to work in Blazor Web Assembly? #62649
-
Given:
I am trying to validate the appsettings.json file of my client web project using AddOptionsWithValidateOnStart. Here is the client project wwwroot/appsettings.json:
And FooSettings.cs:
And Program.cs:
I was expecting/hoping that when I run the application I get an exception complaining that the Bar setting was missing. Instead I can navigate around the Home/Counter/Weather pages without error. If I inject FooSettings into a page, for example:
Then I do get the desired behaviour when I navigate to the Counter page. How I can I get this behaviour across the entire website? Demo repo here: https://github.com/philipmorley/BlazorValidateOptions |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
AddOptionsWithValidateOnStart can register the validation but there is one problem in WASM, it can't handles until you resolove the service yourself, you can fxi it using explicity calling host.Services.GetRequiredService<IOptions>() at startup. sing Microsoft.AspNetCore.Components.WebAssembly.Hosting; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.Services var host = builder.Build(); // force the options to resolve & validate here // if invalid, this will throw and prevent app from running await host.RunAsync(); |
Beta Was this translation helpful? Give feedback.
Thanks, it looks like you have to actually call the options to get the validator to fire. I modified your example slightly:
var foo = host.Services.GetRequiredService<IOptions>();
var bar = foo.Value.Bar;
And when I did this I got the 'Unhandled error has occurred...' error to appear on startup. It's a little bit ugly to have that unused bar variable in my startup code, but I can live with this as a workaround.
Thanks for your help.