0

I'm trying to work with a simple Web API method. When I POST to this I see in Visual Studio's debugger that the method was hit, and cartItemId is populated correctly. But my second parameter, quantity is null.

Here's the Web API:

[HttpPost]
[Route("api/Cart/{cartItemId}")]
[ResponseType("200", typeof(ResponseObject<CartItemDomainModel>)), ResponseType("500", typeof(Exception))]
public async Task<IHttpActionResult> UpdateQuantity(int cartItemId, [FromBody]string quantity)
{
    var result = await _cartService.UpdateCartItemQuantity(cartItemId, Convert.ToInt32(quantity));

    return ...;
}

Here's what Postman is sending:

POST /api/Cart/1 HTTP/1.1
Host: localhost:51335
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 5d4a40f1-794d-46fd-1776-2e0c77979f4a

{
    "quantity":"5"
}
M Kenyon II
  • 4,136
  • 4
  • 46
  • 94

3 Answers3

0

You aren't sending a complex object, just a string.

In postman send '5' instead of "quantity":"5".

You would only do the latter if you had a model class that had a property called 'quantity'.

Ben Hall
  • 1,353
  • 10
  • 19
0

As you are sending a POST request with application/json content type and you have a primitive parameter on your action method, you must pass only a raw JSON string in the body instead of a JSON Object.

So your request should be something like this:

POST /api/Cart/1 HTTP/1.1
Host: localhost:48552
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: d5038684-3a5e-51f6-308c-399dda34457c

"5"

Also, if you know that you parameter is an int, you don't need to pass a string and then convert it, but get it as an int directly from ModelBinder. So if you refactor your action to receive an int parameter:

[HttpPost]
[Route("api/Cart/{cartItemId}")]
[ResponseType("200", typeof(ResponseObject<CartItemDomainModel>)), ResponseType("500", typeof(Exception))]
public async Task<IHttpActionResult> UpdateQuantity(int cartItemId, [FromBody]int quantity)
{
    var result = await _cartService.UpdateCartItemQuantity(cartItemId,quantity));

    return ...;
}

Your request should be like this:

POST /api/Cart/1 HTTP/1.1
Host: localhost:48552
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: d5038684-3a5e-51f6-308c-399dda34457c

5

Hope this helps!

Karel Tamayo
  • 3,690
  • 2
  • 24
  • 30
-1

POST method does not take URL parameters. You should send an object of your properties if you want to use POST method.

Yashasvi
  • 197
  • 1
  • 3
  • 6