简体   繁体   中英

Postman request to C# Web API gives a null property

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"
}

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'.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM