How does the asp.net core API receive parameters

Keywords: JSON Javascript encoding

Introduce various ways of receiving parameters

1. To parse the query parameters in the URL, you need to annotate the controller method parameters with [FromQuery], such as:

[Route("api/[controller]")]
public class PersonController : Controller
{
    //api/Person/GetById?id=123
    [HttpGet("[action]")]
    public string GetById([FromQuery]int id)
    {

    }
    //api/Person/GetByName?firstName=zhangsan&lastName=wang
    [HttpGet("[action]")]
    public string GetByName([FromQuery]string firstName, [FromQuery]string lastName)
    {

    }
    //api/Person/GetByNameAndAddress?firstName=zhangsan&lastName=wang&address=
    [HttpGet("[action]")]
    public string GetByNameAndAddress([FromQuery]string firstName, [FromQuery]string lastName, [FromQuery]string address)
    {
        
    }
}

2. The parameters themselves are part of the path, which can be called routing parameters.

[Route("api/[controller]")]
public class BXLogsController : Controller {
       
        // GET api/values/5  
        [HttpGet("{id}")]  
        publicstring Get(int id)  
        {  
            return"value";  
        }  
}

3. Receiving data from HTTP tables

The two example above is to record parameters in URL. If the number of parameters submitted is large and the content is large, it is not suitable for recording in URL, such as the following two data encoding formats.

  • form encoded data
POST /api/Person/UnProtected HTTP/1.1
Host: localhost:5000
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

FirstName=Andrew&LastName=Lock&Age=31
  • json data
POST /api/Person/UnProtected HTTP/1.1
Host: localhost:5000
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=UTF-8

{"FirstName":"Andrew","LastName":"Lock","Age":"31"}

public class PersonController : Controller
{
    // The action routed to / Person/Index can be bound to form data 
    [HttpPost]
    public IActionResult Index(Person person){
        return DoSomething(person);   
    } 

    // This route is / Person/IndexFromBody that can be bound to JSON data 
    [HttpPost]
    public IActionResult IndexFromBody([FromBody] Person person){
        return DoSomething(person);   
    } 



    //This is not an interface, it's just a private method.
    private IActionResult DoSomething(Person person){
        // do something with the person here
        // ...

        return Json(person);
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Posted by jweissig on Thu, 03 Oct 2019 16:16:19 -0700