Verifying ModelState in ApiController

Here is the POST action in mine ApiController.

public HttpResponseMessage Post(ViewModel model)
    {
        if (!ModelState.IsValid)
        {
            var ResponseMessage = new HttpResponseMessage(HttpStatusCode.XXXXXX
            return ResponseMessage; 
        }

        if (!_service.Create(model))
        {
            var ResponseMessage=new HttpResponseMessage(HttpStatusCode.NotAcceptable);
            return ResponseMessage;
        }
        else
        {
            return new HttpResponseMessage(HttpStatusCode.Created);
        }
    }

Is it possible to enable server-side validation in this way? And, I am sure it Createdshould be returned if everything is in order. But what HttpStatusCode should I return if the ModelState is invalid or some kind of error occurs?

+3
source share
1 answer

Usually it should be 400 - BadRequest.

NotAcceptable - this is when Accept headers cannot be satisfied by the server.

PreConditionFailedlies in the fact that the validation caching conditions are not met. For example, if a PUT request needs to be updated if and only if the ETag value matches the request.


. , 4xx:

return new HttpResponseMessage((HttpStatusCode) 499) 
     {
          ReasonPhrase = "Validation failed"
     };
+2

All Articles