Jose Francis Jose Francis - 1 month ago 8
C# Question

Is there a way to validate a model which is created inside web api controller?

I have a controller where my PUT method uses multipart/form-data as content type and so I am getting the JSON and the mapped class thereby inside the controller.

Is there a way I could validate this model with respect to the annotations I have written in the model class while inside the controller?

public class AbcController : ApiController
{
public HttpResponseMessage Put()
{
var fileForm = HttpContext.Current.Request.Form;
var fileKey = HttpContext.Current.Request.Form.Keys[0];
MyModel model = new MyModel();
string[] jsonformat = fileForm.GetValues(fileKey);
model = JsonConvert.DeserializeObject<MyModel>(jsonformat[0]);
}
}


I need to validate "model" inside the controller.
FYI, I have added required annotations to MyModel().

Answer

Manual model validation:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

class ModelValidator
{
    public static IEnumerable<ValidationResult> Validate<T>(T model) where T : class, new()
    {
        model = model ?? new T();

        var validationContext = new ValidationContext(model);

        var validationResults = new List<ValidationResult>();

        Validator.TryValidateObject(model, validationContext, validationResults, true);

        return validationResults;
    }
}