有没有办法验证在 Web api 控制器内创建的模型?

Jos*_*cis 5 c# model-validation asp.net-web-api

我有一个控制器,我的 PUT 方法使用 multipart/form-data 作为内容类型,因此我在控制器内获取 JSON 和映射的类。

有没有一种方法可以根据我在控制器内部的模型类中编写的注释来验证该模型?

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]);
     }
}
Run Code Online (Sandbox Code Playgroud)

我需要验证控制器内的“模型”。仅供参考,我已向 MyModel() 添加了所需的注释。

And*_*toy 4

手动模型验证:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)