Web框架 --- 解析Web请求 [FromBody] [FromQuery] [FromRoute] [FromHeader]
[FromBody]
- FromBody 属性在使用 application/json 内容类型并在正文中传递 JSON 时使用
- 通常情况下,FromBody 在一个操作中只能用传一个参数。因此,如果在 JSON 正文中传递了多个值,则需要将每个属性添加到一个类中,并将该类用作操作参数的类型.
- 一般只有POST和PUT使用FromBody
public class Customer
{
public string Forename { get; init; }
public string Surname { get; init; }
}
- 这个属性只有在控制器中没有使用 ApiController 属性时才需要使用
[Route("api/from-mvc")]
public class FromMvcController : Controller
{
...
[HttpPost("from-body")]
public IActionResult FromBody([FromBody]string forename)
{
return Ok(new { forename });
}
}
- 如果继承了ApiController可以直接写参数,不需要[FromBody]
[Route("api/from-api")]
public class FromApiController : ApiController
{
...
[HttpPost("from-body")]
public IActionResult FromBody(Customer customer)
{
return Ok(new { customer.Forename, customer.Surname });
}
}
[FromQuery]
- [FromQuery] 用于从uri中的query string (? 后面的部分) 取得参数. query string 可以有多个参数,用 & 符号进行分隔
Uri: /api/from-api/from-query?name="test"&page=4
[Route("api/from-api")]
public class FromApiController : ApiController
{
[HttpGet("from-query")]
public IActionResult FromQuery([FromQuery] string name, [FromQuery] int page)
{
return Ok(new { name, page });
}
...
}
- [FromQuery] 可以是optional. 用 [Optional] attribute 或者给参数设置default value
[Route("api/from-api")]
public class FromApiController : ApiController
{
[HttpGet("from-query")]
public IActionResult FromQuery([Optional][FromQuery] string name)
{
return Ok(new { name, page });
}
...
}
[Route("api/from-api")]
public class FromApiController : ApiController
{
[HttpGet("from-query")]
public IActionResult FromQuery([FromQuery] string name = string.Empty, [FromQuery] int page)
{
return Ok(new { name, page });
}
...
}
[FromRoute] or [FromUri]
[HttpGet, Route("from-route/{category}")]
[HttpGet("from-route/{category}")]
Uri: /api/from-api/from-route/blazor
[Route("api/from-api")]
public class FromApiController : ApiController
{
[HttpGet("from-route/{category}")]
public IActionResult FromRoute([FromRoute] string category)
{
return Ok(new { category });
}
}
Uri: /api/from-api/from-route-with-name/blazor
[HttpGet("from-route-with-name/{category}")]
public IActionResult FromRouteWithName([FromRoute(Name = "category")] string categoryName)
{
return Ok(new { categoryName });
}
[FromHeader]
- 从http request中的header中提取信息 (header中有很多kv pair)
GET /data HTTP/1.1
Host: api.example.com
Authorization: Bearer your-access-token
Content-Type: application/json
Accept: application/json
User-Agent: MyApp/1.0
[ApiController]
[Route("api/from-api")]
public class FromApiController : Controller
{
[HttpGet("from-header")]
public IActionResult FromHeader([FromHeader] string authorization)
{
return Ok(new { authorization });
}
}