Is there a way to test the model created inside the api web controller?

I have a controller where my PUT method uses multipart / form-data as the content type, and so I get the JSON and mapped class this way inside the controller.

Is it possible to test this model for annotations that I wrote 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 check the " model " inside the controller. FYI, I added annotations to MyModel ().

+4
source share
2 answers

Manual model check:

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;
    }
}
+3
source

Suppose you define models in the Product class, for example:

namespace MyApi.Models
{
    public class Product
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

:

 public class ProductsController : ApiController
    {
        public HttpResponseMessage Post(Product product)
        {
            if (ModelState.IsValid)
            {
                 return new HttpResponseMessage(HttpStatusCode.OK);
            }
         }
    }
+3

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


All Articles