locked
Unsupported Media Type RRS feed

  • Question

  • User722039657 posted

    Hi,

    I am using .Net Core 3.1 Web API and jQuery ajax.

    I have 2 actions in Web API Controller - 

    (1) [HttpPost] public async Task<IActionResult> Post([FromBody] string value)

    (2) [HttpPut("{id}")] public async Task<IActionResult> Put(int id, [FromBody] string value)

    I have 2 ajax calls in JS file - 

    (1) $.ajax({
    url: jsClientSettings.getAPI("Home"),
    data: { value: "postval" },
    method: "POST"
    })

    (2) $.ajax({
    url: jsClientSettings.getAPI("Home") + "/" + 1,
    data: { value: "putval" },
    method: "PUT"
    })

    Both ajax calls are throwing same error "415 (Unsupported Media Type)".

    If I remove the action param "[FromBody] string value", the ajax call is succeeding.

    But I need the value params as well. Could you please guide me?

    Monday, August 17, 2020 7:17 AM

Answers

  • User711641945 posted

    Hi Senthil S R,

    If you do not specify the contentType,it is application/x-www-form-urlencoded; charset=UTF-8 by default.But you add the [FromBody] to your action.It needs the application/json contentType.

    Try to add the following code to your ajax:

    $.ajax({
        contentType: "application/json",
        //...
    });

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 17, 2020 9:46 AM
  • User-474980206 posted

    if want to the $.ajax to send json, you shed to pass a json string as data. the default data is url encoded name / value pairs.

    data: JSON.stringify({ value: "putval" }),

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 17, 2020 3:06 PM

All replies

  • User711641945 posted

    Hi Senthil S R,

    If you do not specify the contentType,it is application/x-www-form-urlencoded; charset=UTF-8 by default.But you add the [FromBody] to your action.It needs the application/json contentType.

    Try to add the following code to your ajax:

    $.ajax({
        contentType: "application/json",
        //...
    });

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 17, 2020 9:46 AM
  • User722039657 posted

    jquery.min.js:2 POST http://localhost:62786/api/Home 400 (Bad Request)

    Monday, August 17, 2020 1:19 PM
  • User-474980206 posted

    if want to the $.ajax to send json, you shed to pass a json string as data. the default data is url encoded name / value pairs.

    data: JSON.stringify({ value: "putval" }),

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 17, 2020 3:06 PM