I am following the API instructions from Adam Freeman's "Pro ASP.NET Core MVC 2". I have the following API controller class:
[Route("api/[controller]")]
public class ReservationController : Controller
{
private IRepository repository;
public ReservationController(IRepository repo) => repository = repo;
[HttpGet]
public IEnumerable<Reservation> Get() => repository.Reservations;
[HttpGet("{id}")]
public Reservation Get(int id) => repository[id];
[HttpPost]
public Reservation Post([FromBody] Reservation res) =>
repository.AddReservation(new Reservation
{
ClientName = res.ClientName,
Location = res.Location
});
[HttpPut]
public Reservation Put([FromBody] Reservation res) => repository.UpdateReservation(res);
[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
Reservation res = Get(id);
if(res != null)
{
patch.ApplyTo(res);
return Ok();
}
return NotFound();
}
[HttpDelete("{id}")]
public void Delete(int id) => repository.DeleteReservation(id);
}
The text uses PowerShell to test the API but I would like to use Postman. In Postman, the GET call works. However, I cannot get the POST method to return a value. The error reads 'Status Code: 415; Unsupported Media Type'
In Postman, the Body uses form-data, with:
key: ClientName, value: Anne
key: Location, value: Meeting Room 4
If I select the Type dropdown to "JSON", it reads "Unexpected 'S'"
In the Headers, I have:
`key: Content-Type, value: application/json`
I have also tried the following raw data in the body, rather than form data:
{clientName="Anne"; location="Meeting Room 4"}
The API controller does work and return correct values when I use PowerShell. For the POST method, the following works:
Invoke-RestMethod http://localhost:7000/api/reservation -Method POST -Body (@{clientName="Anne"; location="Meeting Room 4"} | ConvertTo-Json) -ContentType "application/json"
When using Postman with POST and JSON body you'll have to use the raw
data entry and set it to application/json
and data would be like this:
{"clientName":"Anne", "location":"Meeting Room 4"}
Note how both key and value are quoted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With