Kirubakaran Shanmugam
In Web API, how do we ensure whether the parameter passed to the controller api is of required/correct data type?
By Kirubakaran Shanmugam in .NET Core on Jun 25 2023
  • Amit Mohanty
    Jun, 2023 30

    We can ensure that the parameters passed to a controller API are of the required and correct data type by using model binding and data annotations. Model binding is a process that automatically maps the data from an HTTP request to the parameters of a controller method. By applying data annotations to the parameters, you can specify the expected data type and validation rules for the input.

    1. public class SampleRequest
    2. {
    3. [Required]
    4. public string Name { get; set; }
    5. [Range(1, 100)]
    6. public int Age { get; set; }
    7. }
    8. public IHttpActionResult PostSampleData(SampleRequest request)
    9. {
    10. if (!ModelState.IsValid)
    11. {
    12. return BadRequest(ModelState);
    13. }
    14. // Process the valid request here
    15. return Ok();
    16. }

    In the above example, we have a SampleRequest class representing the expected structure of the request body. The Name property is annotated with [Required], indicating that it must have a value. The Age property is annotated with [Range(1, 100)], specifying that it should be an integer between 1 and 100.

    Inside the controller method, the request parameter is automatically populated by the model binding process. By checking the ModelState.IsValid property, we can determine if the incoming data is valid according to the specified data annotations. If the data is not valid, we can return a BadRequest response with the validation. errors.

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS