Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

AddOptionsWithValidateOnStart does not work with Blazor WebAssembly

$
0
0

Given:

  • Framework: .NET 8.0
  • Interactive render mode: WebAssembly
  • Interactivity location: Global
  • Include sample pages: true

I am trying to validate the appsettings.json file of my client web project using AddOptionsWithValidateOnStart.

Here is the client project wwwroot/appsettings.json:

{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"    }  },"Foo": {"Bar": ""  }}

And FooSettings.cs:

using System.ComponentModel.DataAnnotations;namespace ValidateOptions.Client;public class FooSettings{    [Required]    public string Bar { get; set; } = string.Empty;}

And Program.cs:

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;using ValidateOptions.Client;var builder = WebAssemblyHostBuilder.CreateDefault(args);builder.Services    .AddOptionsWithValidateOnStart<FooSettings>()    .Bind(builder.Configuration.GetSection("Foo"))    .ValidateDataAnnotations();await builder.Build().RunAsync();

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:

@page "/counter"@using Microsoft.Extensions.Options@inject IOptions<FooSettings> AppSettings<PageTitle>Counter</PageTitle><p>AppSettings = @AppSettings.Value.Bar</p>

Then I do get the desired behaviour when I navigate to the Counter page, see screenshot. How I can I get this behaviour across the entire website?

enter image description here


Viewing all articles
Browse latest Browse all 4839

Trending Articles