繁体   English   中英

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

[英]POSTMAN POST Request Returns Unsupported Media Type

我遵循 Adam Freeman 的“Pro ASP.NET Core MVC 2”中的 API 说明。 我有以下 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);
}

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

在 Postman 中,Body 使用 form-data,其中:

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

如果我 select Type 下拉菜单为“JSON”,它显示为“Unexpected 'S'”

在标题中,我有:

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

我还在正文中尝试了以下原始数据,而不是表单数据:

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

当我使用 PowerShell 时,API controller 确实工作并返回正确的值。对于 POST 方法,以下工作:

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

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

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

请注意如何引用键和值。

对于使用Patch方法,如果邮递员的原始“正文”部分像

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

和数据输入为application / json

Postman中的Patch方法的屏幕截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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