[Note] Model binding

less than 1 minute read

![

Introduction

This is a memo when I researched Model Binding of ASP.NET Core. ..

Basic operation

PetsController.cs


using Microsoft.AspNetCore.Mvc;

namespace webapi01.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PetsController : ControllerBase
    {
        public class Pet
        {
            public int Id { get; set; }

            public string Name { get; set; }
        }

        //The values of path parameters and query parameters can be obtained by preparing arguments with the same name in the action method.(Can also be obtained from HttpContext)
        //Parameters are not case sensitive
        // http://localhost:5000/pets/2?DogsOnly=true
        [HttpGet("{id}")]
        public ActionResult<Pet> GetById(int id, bool dogsOnly) // id=2, dogsOnly=true
        {
            return new Pet()
            {
                Id = id,
                Name = $"huga{id}"
            };
        }

        //For complex type arguments, the value of each property is retrieved from the request body
        //The format of the request body is specified by the Consumers attribute or Content-Use the value of the Type header
        [HttpPost]
        public ActionResult<string> Post(Pet pet)
        {
            //Register the received data in the DB ...

            //201 Returns Created. Add Location to the response header and return the URL of the resource.
            return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
        }
    }
}

image.png