1

When I send data from JavaScript to the API (asp.net WebApi) I get the following error back: The request entity's media type 'text/plain' is not supported for this resource. I want to send the data in the JSON format.

The JavaScript code:
let newReservation = {
    "name" : name,
    "emai" : email,
    "phone" : phone,
    "people" : people,
    "date" : date,
    "time" : time
}

data = JSON.stringify(newReservation)
reservation = JSON.parse(data)

let Http = new XMLHttpRequest
let url = 'https://localhost:44320/api/reservations'

Http.open('POST', url)
Http.send(reservation)
console.log()
Http.onreadystatechange=(e)=>{
    console.log(Http.responseText)
}

The C# code:
Controller:
public IHttpActionResult Post([FromBody]Reservation reservation)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        expressoDbContext.Reservations.Add(reservation);
        expressoDbContext.SaveChanges();
        return StatusCode(HttpStatusCode.Created);
    }
 Config:
 config.Formatters.Remove(config.Formatters.XmlFormatter);
 config.Formatters.JsonFormatter.SerializerSettings.Formatting = 
 Newtonsoft.Json.Formatting.Indented;
mr pixel
  • 27
  • 2
  • 5
  • This answer will help you to add `Content-Type` header. https://stackoverflow.com/a/37454528/2696422 – fumiya.f Oct 30 '19 at 16:38

2 Answers2

1

You need to set the Content-Type header in your XMLHttpRequest:

Http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
EylM
  • 5,967
  • 2
  • 16
  • 28
1

Set the HTTP request header to **Content-Type: application/json**. You have to add this line HTTP.setRequestHeader("Content-Type", "application/json"); to your code.

shilpa syal
  • 56
  • 1
  • 5