Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an error response in the case of a null model

In my ASP.NET MVC API application, I can return a helpful ErrorResponse if a few of my Required fields are missing:

return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

-

"Message": "The request is invalid.",
        "ModelState": {
            "myModel.FooA": [
                "The FooA is required."
            ],
            "myModel.FooC": [
                "The FooC property is required."
            ],
            "myModel.FooD": [
                "The FooD property is required."
            ]
        }

However as this answer confirms, a NULL model will validate. As I don't allow this, how can I return an equally helpful error response stating all the values that are required? I know that I can manually add a ModelError for each property, but I suspect there may be a way that CreateErrorResponse can do this for me.

like image 899
Jonathan Avatar asked Aug 14 '13 15:08

Jonathan


1 Answers

Are you using mvc3 or web-api? your tags indicate you're using mvc but your opening sentence implies web-api. If using mvc3 you can use the following:

In your controller before your call to ModelState.IsValid add:

if (modelObj == null)
{
    ModelState.Clear();
    var blankModel = new MyClass();
    TryValidateModel(blankModel);
    return View("About", blankModel);        
}

If you're using web-api and assuming you're using System.ComponentModel.DataAnnotations you can use the following:

ModelState.Clear();

var model = new MyClass();
var results = new List<ValidationResult>();
Validator.TryValidateObject(model, new ValidationContext(model, null, null), 
                                                                 results, true);

var modelState = new ModelStateDictionary();
foreach (var validationResult in results)
    modelState.AddModelError(validationResult.MemberNames.ToArray()[0],
                                                 validationResult.ErrorMessage);

return Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
like image 105
wal Avatar answered Oct 12 '22 20:10

wal