Why is my null model being tested?

I have a model:

public class Foo { [Required] public string Bar1 { get; set; } public string Bar2 { get; set; } } 

which I check in my ASP.NET MVC API:

 public HttpResponseMessage Post(Foo foo) { if (ModelState.IsValid) { // Valid } else { // Invalid } } 

If I send POST without key / value pairs (making myModel null), my ModelState as noted is valid. Why is this? It correctly marks it as invalid if I provide only the Bar2 key.

+4
source share
1 answer

This is by design. If your model is zero, no validation is performed. If, on the other hand, your model is not null, but the Bar1 property is null or an empty string, you will receive a validation error.

For example, you get a validation error with the following payload:

 { "Bar2": "Bazinga" } 

or with this:

 { "Bar1": null, "Bar2": "Bazinga" } 

or with this:

 { "Bar1": "", "Bar2": "Bazinga" } 
+2
source

Source: https://habr.com/ru/post/1497050/


All Articles