Stan Stan - 4 months ago 16
C# Question

ModelState.IsValid even when it should not be?

I have API where I need to validate my user model. I choose an approach where I create different classes for Create/Edit actions to avoid mass-assignment and divide validation and actual model apart.

I don't know why but

returns true even when it should not. Am I doing something wrong?


public HttpResponseMessage Post(UserCreate user)
if (ModelState.IsValid) // It's valid even when user = null
var newUser = new User
Username = user.Username,
Password = user.Password,
Name = user.Name
return Request.CreateResponse(HttpStatusCode.Created, new { newUser.Id, newUser.Username, newUser.Name });
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);


public class UserCreate
public string Username { get; set; }
public string Password { get; set; }
public string Name { get; set; }

Debug proof



The ModelState.IsValid internally checks the Values.All(modelState => modelState.Errors.Count == 0) expression.

Because there was no input the Values collection will be empty so ModelState.IsValid will be true.

So you need to explicitly handle this case with:

if (user != null && ModelState.IsValid)


Whether this is a good or bad design decision that if you validate nothing it will true is a different question...