【发布时间】:2019-04-18 12:00:14
【问题描述】:
通过这种使用 PUT 动词的简单方法来使用 ASP.Net Core 2.2 和 Postman 更新项目,我创建了如下模型:
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
}
一个控制器方法如下:
// PUT: api/PutProduct/5
[HttpPut("api/[action]/{id}")]
public async Task<IActionResult> PutProduct(Guid id, Product Product)
{
if (id != Product.Id)
{
return BadRequest();
}
_context.Entry(Product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
// return NoContent();
return AcceptedAtAction("GetProduct", new { id = Product.Id, name = Product.Name }, Product);
}
然后是一个JSON体如下:
{
"name": "Product (Edited)"
}
现在,当我单击 Postman PUT 方法时,它会返回 202 状态,但不会使用新值更新“名称”字段,而是将其清除。
如果我添加 [FromBody] 如下,它返回 400 错误(错误请求):
public async Task<IActionResult> PutProduct(Guid id, [FromBody] Product Product)
我在这里做错了什么?
【问题讨论】:
-
你的控制器是用
[ApiController]装饰的吗?如果我没看错,400 是预期的响应,因为您没有在邮递员请求中传递 id。 -
@k3davis 我在 url 中传递了一个 id,我不需要 [ApiController] 装饰,因为我在方法路由中指定了它。
标签: c# asp.net-core postman http-put