如何避免将空实体对象传递给Web API方法

时间:2018-08-24 10:25:01

标签: asp.net-web-api asp.net-web-api2

我有如下的Web api方法

public bool UpdateValidations([FromBody] ValidationKeyEntity validationKey)
{
    if (ModelState.IsValid)
    { 
        //my code here
    }
}

public class ValidationKeyEntity
{
    public int ValidationKeyId { get; set; }

    [MaxLength(Constants.maxStringLength)]
    public string Name { get; set; }

    public int DisplayId { get; set; }

    [MaxLength(Constants.maxStringLength)]
    public string CreatedBy { get; set; }
}

我正在使用Postman进行测试。我将与ValidationKeyEntity对象不同的json作为参数传递给{“ Vishal”:“ vishal”}。 但我的 ModelState.IsValid仍返回true

如何避免接受“ ValidationKeyEntity”对象以外的其他json对象?

1 个答案:

答案 0 :(得分:0)

  1. 使用RequiredAttribute将属性标记为required

    public class ValidationKeyEntity
    {
        [Required]
        public int ValidationKeyId { get; set; }
    
        [Required]
        public string Name { get; set; }
    
        [Required]
        public int DisplayId { get; set; }
    
        [Required]
        public string CreatedBy { get; set; }
    }
    
  2. 全局设置MissingMemberHandling以处理废物属性:

    var httpConfiguration = new HttpConfiguration();
    
    httpConfiguration
                    .Formatters
                    .JsonFormatter
                    .SerializerSettings
                    .MissingMemberHandling = MissingMemberHandling.Error;