dotnet / dotnet/aspnetcore

`ValidateOnStartup` does not work when using `WebHost.CreateDefaultBuilder`

Open
#58,100 0 comments 0 reactions 0 assignees View on GitHub
area-networking
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

The `ValidateOnStartup` method which can be called when setting up a particular `Options` instance has no effect when the application is being executed by a `WebHost` instance.

Apparently, `WebHost` never implemented support for this validation like `Host` does in the `Microsoft.Extensions.Hosting` package.

In this scenario, `ValidateOnStartup` will run, but have no effect, since the underlying `IStartupValidator` service will never be invoked anywhere.

### Expected Behavior

I would expect either of the 2 scenarios:
1. Options validation takes place during startup normally, and throws the expected exception when validation fails, by executing all `IValidateOptions` services for options that opted-into the validate-on-start mechanism by calling `ValidateOnStart`
2. An exception should be thrown to indicate that startup validation is not supported on `WebHost` when `ValidateOnStart` is called.

### Steps To Reproduce

https://github.com/julealgon/julealgon.AspNetOptionValidationWebHostRepro

1. Create a web host using the `WebHost.CreateDefaultBuilder` method.
2. Add an `IValidateOptions` implementation to the container using `ConfigureOptions`
3. Add some option instance to the services container using `AddOptions`
4. Call `ValidateOnStart` on the `OptionsBuilder` object returned by `AddOptions`
5. Run the web application
6. Notice that the `IValidateOptions` implementation from 2 is never called

### Exceptions (if any)

_No response_

### .NET Version

net472

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.