Web Api HTTPPost does not accept int

I'm trying to just pass body a int , and it doesn't work. Why do I need to create a class with a property of type int? (then it works)

WORKS

 [HttpPost] [Route("api/UpdateMainReversed")] public IHttpActionResult UpdateMainVerified(DataAccess.Entities.RequestMain mainValues) { ....} 

DO NOT WORK

 [HttpPost] [Route("api/UpdateMainReversed")] public IHttpActionResult UpdateMainVerified(int mainId) { ....} 

Testing with Postman

http: // localhost: 13497 / api / UpdateMainReversed

Body

 { "mainId" : 1615 } 
+5
source share
2 answers

1. Your [HttpPost] expects an int, but from the body you are passing a json object. you must pass the json string as shown below. No need to mention parameter name

enter image description here

2. you must use [FromBody] as below

 [HttpPost] public void UpdateMainVerified([FromBody] int mainid) { } 

this link explains well

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

+6
source

Set the FromBody attribute. To force the Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

Details Link

 [HttpPost] [Route("api/UpdateMainReversed")] public IHttpActionResult UpdateMainVerified([FromBody] int mainId) { ....} 
+1
source

Source: https://habr.com/ru/post/1265574/


All Articles