简体   繁体   中英

POSTMAN POST Request Returns Unsupported Media Type

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.

For using Patch method it will be better if the raw Body section of postman be like

[   
    {
        "op": "replace", "path": "/firstName" , "value": "FirstName",
    }
]

and data entry be application/json

Postman中的Patch方法的屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM