我有如下的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对象?
答案 0 :(得分:0)
使用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; }
}
全局设置MissingMemberHandling以处理废物属性:
var httpConfiguration = new HttpConfiguration();
httpConfiguration
.Formatters
.JsonFormatter
.SerializerSettings
.MissingMemberHandling = MissingMemberHandling.Error;