2

I have an API with a HttpPost function, but when I call the API from JavaScript, the method variables are always 0. I use [FromBody], is this right?

Function:

[HttpPost("API/AddToCart")]
public async Task AddToCartAsync([FromBody] int id, [FromBody] int count)

The json I pass to the function:

{ "id": id, "count": count }

The function gets called but without the supplied values. Everything works if I use HttpGet and passes the data as query.

Any tips ?

1
  • 1
    See here - ” When a parameter has [FromBody], … at most one parameter is allowed to read from the message body. So this will not work:” . Try defining a simple object with the two properties and read that from the body. Commented Apr 16, 2022 at 19:20

1 Answer 1

3

Created a model to receive the values.

Model:

public class AddToCartModel
{
    public int Id { get; set; }
    public int Count { get; set; }
}

Action:

public async Task AddToCartAsync([FromBody] AddToCartModel data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.