skip to Main Content

I am trying to capture a JSON array of string from POST Request in web api.

[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CancelItems([FromBody] List<string> items)
{
    //codes
}

But I am getting null in items.

Post Body:

{
    "items":[
        "1034908029943809497", "1034908029943809494"
    ]

}

3

Answers


  1. Just send the strings:

    [
        "1034908029943809497", "1034908029943809494"
    ]
    
    Login or Signup to reply.
  2. Try this:

    [HttpPost]
    [Route("")]
    public async Task<IHttpActionResult> CancelItems([FromBody] JObject jObject)
    {
          var model = jObject.ToObject<FromQuery>();
          //replace FromQuery with your model class
          //code ....
    }
    
    Login or Signup to reply.
  3. I am trying to capture a JSON array of string from POST Request in web
    api.

    Based on your shared code snippet, It has appreared that you want to get your items array on your web api controller.

    Apparently, two context need to clarify here, either API controller need to construct as per your request Definition or request Definition need to modify based on your API.

    Way: 1: Define API based on request body:

    Considering your request body which is strongly type of items object so based on this if you want to send request as per your current requst body; Thus, a strongly type POCO class need to be introduced.

    Let’s take a look in action.

    Strongly Type Model:

    public class StringCompatibleClass
        {
    
            public List<string> items { get; set; }
        }
    

    Controller:

            [HttpPost]
            public async Task<IHttpActionResult> CancelItems([FromBody] StringCompatibleClass items)
            {
                return Ok(items);
            }
    

    Output:

    enter image description here

    Way: 2: Modify request body based on API Definition:

    Based on your current API Definition if you prefer to persist with API defination as it is then you would require to change request body as following which alrady shown by another contributor:

    [
            "1034908029943809497", "1034908029943809494"
    ]
    

    Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search