Search code examples
c#jqueryasp.net-core-mvcasp.net-core-7.0

ASP.NET Core MVC Empty Request Body .NET 7


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.


Solution

  • $.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