[英]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"}
請注意如何引用鍵和值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.