欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net core API 如何接收参数

程序员文章站 2024-02-20 00:02:16
...

1、要解析URL中的查询参数,需要用[FromQuery]注释控制器方法参数

[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、参数本身就是路径的一部分,可以称之为路由参数

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

3、接收来自HTTP表体中数据

上面的两个示例都是将参数记录在 URL中,假如提交的参数数量较多,内容较大,都是不适合记录在URL中,比如下面的两种数据编码形式

  • 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"}

对于包含多个字段参数,可以采用模型绑定机制,让HTTP表体中的参数自动转化为对象,方便处理。

public class PersonController : Controller
{
    // 这个路由为/Person/Index的action可以绑定到 form数据 
    [HttpPost]
    public IActionResult Index(Person person){
        return DoSomething(person);   
    } 

    // 这个路由为/Person/IndexFromBody可以绑定到JSON数据 
    [HttpPost]
    public IActionResult IndexFromBody([FromBody] Person person){
        return DoSomething(person);   
    } 



    //这个不是接口,只是一个私有方法
    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; }
}

参考:https://andrewlock.net/model-binding-json-posts-in-asp-net-core/

相关标签: asp.net core