.NET 8 introduced new attributes, AllowedValues and DeniedValues, as part of the System.ComponentModel.DataAnnotations namespace. These attributes simplify input validation by specifying which values are permitted and which are not for your API parameters.
The code sample is available in the comments.
What are AllowedValues
and DeniedValues
?
- AllowedValues: Ensures that only specified values are accepted.
- DeniedValues: Ensures that specified values are not accepted.
[AllowedValues("Red", "Yellow", "Green")]
[DeniedValues("Black", "White")]
public string? AlertValue { get; set; }
Explanation
-
AlertValue string: Uses
AllowedValues
to ensure only "Red", "Yellow", or "Green" are accepted. UsesDeniedValues
to reject "Black" and "White".
Conclusion
Using AllowedValues
and DeniedValues
attributes in .NET 8 simplifies input validation in your API, ensuring that only valid values are accepted and invalid ones are rejected. This enhances the robustness and reliability of your application.
Top comments (1)
code sample
github.com/mohamedtayel1980/DotNet...