Problem statement
Add validation rules to an options class and check them when the app starts, so a bad setting stops the app with an error that names it.
Requirements
The WebhookController and the Webhook section in appsettings.json are already provided. Your task has two parts: add validation attributes in WebhookDeliveryApi/Options/WebhookOptions.cs, and register the options in WebhookDeliveryApi/Configuration/WebhookOptionsRegistration.cs.
Data annotations are attributes such as [Required] and [Range] that describe a valid value. The options pattern can check them, and with fail-fast validation it does so while the app starts, not later when a request first reads the setting.
WebhookOptions
Add attributes from System.ComponentModel.DataAnnotations so that:
- EndpointUrl is a web address starting with http:// or https://, such as https://hooks.example.com/deliveries. An empty value or a value such as hooks-example-com is invalid
- MaxAttempts is from 1 to 10
- TimeoutSeconds is from 1 to 120
- SigningKey is set and has at least 16 characters
WebhookOptionsRegistration
- Register WebhookOptions with AddOptions, bound to the section named by WebhookOptions.SectionName
- Its data annotations are checked when the app starts, so an invalid setting stops the app with an error naming each invalid member
WebhookController (provided)
- GET /webhook/settings answers 200 with endpointUrl, maxAttempts, timeoutSeconds and signingKeyLength
Sample Requests & Responses
GET /webhook/settings
Response (200 OK):
{
"endpointUrl": "https://hooks.example.com/deliveries",
"maxAttempts": 3,
"timeoutSeconds": 30,
"signingKeyLength": 21
}
Starting the app with MaxAttempts set to 0 stops it before it serves any request:
Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for 'WebhookOptions' members: 'MaxAttempts' with the error: 'The field MaxAttempts must be between 1 and 10.'.
