简体   繁体   English

对C#Web API的邮递员请求提供了空属性

[英]Postman request to C# Web API gives a null property

I'm trying to work with a simple Web API method. 我正在尝试使用简单的Web API方法。 When I POST to this I see in Visual Studio's debugger that the method was hit, and cartItemId is populated correctly. 当我POST到这一点,我在Visual Studio中的调试器,该方法被击中看看, cartItemId正确填充。 But my second parameter, quantity is null . 但是我的第二个参数, quantitynull

Here's the Web API: 这是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". 在邮递员中发送“ 5”而不是“数量”:“ 5”。

You would only do the latter if you had a model class that had a property called 'quantity'. 仅当您拥有一个具有称为“ 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. 当您发送具有application / json内容类型的POST请求,并且在action方法上具有原始参数时,您必须在主体中仅传递原始JSON字符串,而不是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. 另外,如果您知道参数是一个int,则不需要传递字符串然后进行转换,而是直接从ModelBinder以int形式获取它。 So if you refactor your action to receive an int parameter: 因此,如果您重构操作以接收一个int参数:

[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. POST方法不采用URL参数。 You should send an object of your properties if you want to use POST method. 如果要使用POST方法,则应发送属性对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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