Validate input to a POST request?

Viewed 1005

I have made a controller for a REST POST api endpoint, is as following

public IActionResult POST([FromBody]Person person) 
{ 
    ....
} 

and where Person is defined as

public class Person 
{
   public string Name {get; set;}
   public int Age {get; set;}
}

meaning that the post request is able deserialise an input like this

{
  "Name": "Peter", 
  "Age": 2
}

without any problems...

Problems occurs though when I pass something like

{
  "Name": "Peter", 
  "Age": 2, 
  "Error": 123123123
}

It still creates an Person which have the first two filled out..

I would like to trigger an error here stating that the input format is wrong.

I am storing the first input - and then use it to compare the next input based on the first one. If they are the same - nothing should happen.

But since the last input contains a invalid field but the actual instance the input created is completely similar to the first one - I get an error on they are not equal?

I assume the error statement in the JSON is somehow stored in the new instance? but how do i make sure that the input is being validated before the controller created an instance given the JSON input?

1 Answers

1) to validate your Person model, you could have something like

using System.ComponentModel.DataAnnotations;
public class Person
{
    [Required]
    [StringLength(250, MinimumLength = 2)]
    public string Name { get; set; }

    [Required]
    [Range(1, 121)]
    public int Age { get; set; }
}

and inside controller's POST action you can use if(!ModelState.IsValid){.....}

2) to compare if two Person instances are equal you could override Equals():

public class Person
{
    ...
    ...
    public override bool Equals(object obj) =>
        (obj is Person otherPerson) ? (Name,Age) == (otherPerson.Name,otherPerson.Age): false;
}

here current instance's Name and Age are compared to other instance's Name and Age. It will allow using if ( person.Equals ( someOtherPErsonInstance ) ){....}

3) if you need to make sure extra fields are not present in the POST request, you could add custom implementation IModelBinder, or accept raw data in POST action, then, parse and check.

Related