首页 文章

POSTMAN POST请求返回不支持的媒体类型

提问于
浏览
2

我正在遵循Adam Freeman的“Pro ASP.NET Core MVC 2”的API说明 . 我有以下API控制器类:

[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);
}

该文本使用PowerShell来测试API,但我想使用Postman . 在Postman中,GET调用有效 . 但是,我无法让POST方法返回值 . 错误显示为“状态代码:415;不支持的媒体类型'

在Postman中,Body使用表单数据,其中:

key: ClientName, value: Anne
key: Location, value: Meeting Room 4

如果我选择类型下拉列表为“JSON”,则会显示“Unexpected'S”

在 Headers 中,我有:

`key: Content-Type, value: application/json`

我还在体内尝试了以下原始数据,而不是表单数据:

{clientName="Anne"; location="Meeting Room 4"}

使用PowerShell时,API控制器可以正常工作并返回正确的值 . 对于POST方法,以下工作:

Invoke-RestMethod http://localhost:7000/api/reservation -Method POST -Body (@{clientName="Anne"; location="Meeting Room 4"} | ConvertTo-Json) -ContentType "application/json"

1 回答

  • 2

    当使用Postman与POST和JSON主体时,你将不得不使用 raw 数据条目并将其设置为 application/json ,数据将如下所示:

    {"clientName":"Anne", "location":"Meeting Room 4"}
    

    请注意如何引用键和值 .

相关问题