0

I have below web api method as below

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; }
}

I am doing testing using Postman .I am passing different json than ValidationKeyEntity object as { "Vishal": "vishal" } as parameter . But still my ModelState.IsValid returns true.

How can I avoid accepting other json object than "ValidationKeyEntity" object?

Andriy Tolstoy
  • 5,690
  • 2
  • 31
  • 30
Vishal Pawar
  • 356
  • 4
  • 12
  • 1
    Check this link: https://stackoverflow.com/questions/881281/what-is-modelstate-isvalid-valid-for-in-asp-net-mvc-in-nerddinner – Sahil Sharma Aug 24 '18 at 10:29
  • I suggest you create your own ModelBinder and use it in place of [FromBody] in your method. You are more than likely going to perform validation anyway and you work with the framework pipeline so you know when you get into your method that you have a "valid" object, whatever "valid" means to you. IMO ModelBinders are an underused aspect of ASP. – No Refunds No Returns Aug 27 '18 at 13:51

1 Answers1

0
  1. Use RequiredAttribute to mark the properties as 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. Set MissingMemberHandling globally to handle waste properties:

    var httpConfiguration = new HttpConfiguration();
    
    httpConfiguration
                    .Formatters
                    .JsonFormatter
                    .SerializerSettings
                    .MissingMemberHandling = MissingMemberHandling.Error;
    
Andriy Tolstoy
  • 5,690
  • 2
  • 31
  • 30