17

I am trying to just pass in body a int and it does not 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
}

2 Answers2

35

1.Your [HttpPost] expects a int but from body you are passing a json object. you should pass json string like below. No need to mention parameter name

enter image description here

2.you should use [FromBody] as below

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

    }

this link explains it well

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

Boopathy T
  • 537
  • 3
  • 8
  • NICE JOB. I read several articles and was ready to give up as I could pass in a string instead of int to string mainid ... but value was null. THIS solution actually works! thx –  Mar 16 '17 at 22:42
  • Also if using axios, post data as axios.post('/UpdateMainVerified', mainId) not as json i.e. axios.post('/UpdateMainVerified', {mainId: mainId}) – Michael Sep 10 '21 at 22:05
3

Set FromBody Attribute.

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

For details Link

[HttpPost]
[Route("api/UpdateMainReversed")]
public IHttpActionResult UpdateMainVerified([FromBody] int mainId)
    {  ....}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Muhammad Saqlain
  • 2,112
  • 4
  • 33
  • 48
  • { "message": "The request is invalid.", "messageDetail": "The parameters dictionary contains a null entry for parameter 'mainId' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult AddProduct(Int32)' i –  Mar 16 '17 at 19:52
  • 1
    set Content-Type: application/x-www-form-urlencoded – Muhammad Saqlain Mar 16 '17 at 20:11
  • then it would no longer be JSON Muhammad ... I'm in your situation user6321478 , if anyone has a fix – Max Dec 10 '18 at 16:06