首页 > 解决方案 > 如何避免将空实体对象传递给 web api 方法

问题描述

我有下面的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 对象?

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

解决方案


  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;
    

推荐阅读