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

时间:2018-05-03 13:31:54

标签: c# api asp.net-core postman

我正在遵循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;不支持的媒体类型&#39;

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

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

如果我选择类型下拉菜单&#34; JSON&#34;,则会显示&#34;意外&#39;&#39;&#34;

在标题中,我有:

`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"

2 个答案:

答案 0 :(得分:4)

使用Postman与POST和JSON正文时,您必须使用raw数据条目并将其设置为application/json,数据将如下所示:

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

注意如何引用键和值。

答案 1 :(得分:0)

对于使用Patch方法,最好将邮递员的原始“正文”部分设为

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

和数据输入为application / json

Screenshot for Patch method in Postman