0

I get an empty Request.Body in the controller when I make a request to the controller from the frontend part, but if I use Postman, then everything works. When I sent request from Firefox, request body is not empty.

Here's my code (JS):

$("#save_changes").on("click", function () {
    var obj = getOrderJsonData();
    $.ajax({
        type: "POST",
        url: "/studentflow/save/" + String($("#current_order").prop("value")),
        data: JSON.stringify(obj),
        success: function (response) {
            alert("Saved")
        }
    });
});

ASP.NET Core 7 controller:

[HttpPost]
[Route("/studentflow/save/{id?}")]
public async Task<IActionResult> SaveFlowChanges(string id)
{
    bool parsed = int.TryParse(id, out int orderId);

    if (!parsed)
    {
        return BadRequest("id is undefined");
    }

    using (var stream = new StreamReader(Request.Body))
    {
        var jsonString =  await stream.ReadToEndAsync();
        Console.WriteLine(jsonString);
        var result = await Order.GetOrderForConduction(orderId, jsonString);

        if (result.IsSuccess)
        {
            var order = result.ResultObject;
            await order.ConductByOrder();
            return Ok();
        }
        else
        {
            return BadRequest(result.Errors?.ErrorsToString() ?? "");
        }
    }
}

I tried reading Request.Body differently, changing the AJAX request, but nothing worked, I still get the same error.

2
  • When you debug, what do you observe in the obj variable? Commented Jan 23, 2024 at 19:59
  • When I use Postman it displays: {"Moves":[{"StudentId":5,"GroupToId":2}]}, when Jquery sends request (request has the same body), nothing is recieved from body. Commented Jan 23, 2024 at 20:02

1 Answer 1

0
$.ajax({
    type: "POST",
    url: "/studentflow/save/" + String($("#current_order").prop("value")),
    data: JSON.stringify(obj),
    contentType: "application/json", // Specify the content type
    success: function (response) {
        alert("Saved")
    }
});

specify the content type contentType: "application/json" in ajax call

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! It finally worked! I have never used this property before, but, it always worked...

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.