无法使用 httpclient 从 angular 到 WebAPI post 整数值
Cannot post integer value from angular with httpclient to WebAPI
totalPrice
始终为 0,我可以 post 任何实体,但我不能 post 只是 int 或字符串。
我认为它大约 JSON
但不确定如何 post 只有一个整数。
当我使用 swagger
或 postman
post 整数时,它会起作用。
谢谢。
默认情况下 Angular 发送请求内容类型 application/json
因此您的 dotnet webapi 操作期望某种模型与该 JSON 绑定。使用 [FromBody]
属性应该可以解决您的问题。
这是我刚刚创建的用于测试的示例。
API:
[HttpPost("add")]
public IActionResult Add([FromBody] int totalPrice)
{
return Ok("RESULT: " + totalPrice);
}
POST请求:
POST https://localhost:5001/weatherforecast/add
Content-Type: application/json
8000
回复:
POST https://localhost:5001/weatherforecast/add
HTTP/1.1 200 OK
Date: Wed, 07 Apr 2021 19:39:25 GMT
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
RESULT: 8000
Response code: 200 (OK); Time: 52ms; Content length: 12 bytes
totalPrice
始终为 0,我可以 post 任何实体,但我不能 post 只是 int 或字符串。
我认为它大约 JSON
但不确定如何 post 只有一个整数。
当我使用 swagger
或 postman
post 整数时,它会起作用。
谢谢。
默认情况下 Angular 发送请求内容类型 application/json
因此您的 dotnet webapi 操作期望某种模型与该 JSON 绑定。使用 [FromBody]
属性应该可以解决您的问题。
这是我刚刚创建的用于测试的示例。
API:
[HttpPost("add")]
public IActionResult Add([FromBody] int totalPrice)
{
return Ok("RESULT: " + totalPrice);
}
POST请求:
POST https://localhost:5001/weatherforecast/add
Content-Type: application/json
8000
回复:
POST https://localhost:5001/weatherforecast/add
HTTP/1.1 200 OK
Date: Wed, 07 Apr 2021 19:39:25 GMT
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
RESULT: 8000
Response code: 200 (OK); Time: 52ms; Content length: 12 bytes