Is it possible to do some validation using attributes on simple parameters, like:
[HttpGet("test/{type}")]
public ActionResult GetSomeData([Range(0,2)]byte type)
{
if (!ModelState.IsValid)
{
// isValid is always TRUE
}
...
}
When you call /controller/test/4
, IsValid
is always TRUE
.
Is there a cleaner way to do that?
As of version 2.1, this functionality is now available out of the box; data annotations on action parameters will also be respected when calling ModelState.IsValid
in the same way that they are on models.
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#top-level-node-validation
If you annotate your class with the ApiController
attribute, validation will also be performed automatically, and a 400 Bad Request will be returned with details of the invalid data without having to call ModelState.IsValid
yourself.
https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#automatic-http-400-responses
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With