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;