我正在遵循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"