asp.net-corepostasp.net-web-apipostman

POST request working on Postman but not using jQuery POST


I am writing a dotnet core web API. The POST method on controller looks like:

// POST: api/SurveyUserResponses
        [HttpPost]
        public async Task<IActionResult> PostSurveyUserResponse([FromBody] List<SurveyUserResponse> surveyUserResponse)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.SurveyUserResponse.AddRange(surveyUserResponse);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (SurveyUserResponseExists(surveyUserResponse[0].UserId))
                {
                    return new StatusCodeResult(StatusCodes.Status409Conflict);
                }
                else
                {
                    throw;
                }
            }

            return new StatusCodeResult(StatusCodes.Status201Created);
        }

This works fine 201 created when I use Postman to send this json :

[
    {
        "userId": 1,
        "qId": 1,
        "optionId": 0,
        "response": "Suryansh",
        "surveyCreatorOptions": null,
        "user": null
    },
    {
        "userId": 1,
        "qId": 2,
        "optionId": 0,
        "response": "suryansh",
        "surveyCreatorOptions": null,
        "user": null
    }
   
]

But when I use $.post("https://localhost:44366/api/surveyuserresponses/postsurveyuserresponse",JSON.stringify(jsonArr)); Chrome console shows 400(Bad Request)

For figuring out the problem I even tried copying the form data and sent it through Postman it works just fine. I can't figure out the issue.


Solution

  • But when I use $.post("https://localhost:44366/api/surveyuserresponse/postsurveyuserresponse",JSON.stringify(jsonArr));

    Since your server expects a payload of JSON, you need specify a header of Content-Type for the request:

    $.ajax({
        type: "POST",
        url: "https://localhost:44366/api/surveyuserresponses/postsurveyuserresponse",
        contentType: "application/json",,
        data: JSON.stringify(jsonArr),
        success: function(result){  /*...*/  }
    });