ASP.NET Core API - How to accept JSON array in POST

baylf2000 20 Reputation points
2023-01-17T06:23:46.84+00:00

I'm following along with a tutorial for an ASP.NET Core API. I have the following in my controller, which successfully accepts a single Mission item. I'd like to adapt it to be able to accept a JSON array with multiple missions, as well as just a single one.

I know it will involve a List, but I'm new to C#, so I'm not sure what that would look like.

[HttpPost]
public async Task<ActionResult<Mission>> PostMission(Mission mission)
{
    if (_context.Missions == null)
    {
        return Problem("Entity set 'MissionContext.Missions' is null.");
    }
    _context.Missions.Add(mission);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetMission), new { id = mission.ID }, mission);
}
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Xinran Shen - MSFT 2,091 Reputation points
    2023-01-17T07:57:02.24+00:00

    Hi @baylf2000,

    If you want to receive multiple missions, you can just add List<T> in your parameter,

    public async Task<ActionResult<Mission>> PostMission(List<Mission> mission)
    {
    }
    

    Demo:

    Here I send json array in request body:

    User's image

    Then I can receive json array in my action:

    23117

    If you receive data from form, you don't need to add [FromBody] attribute before your parameter like what I post in gif.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Xinran Shen

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.