"Message":在.NET API中"The requested resource does not support http method 'POST'." JSON返回



>我收到以下消息:

请求的资源不支持 http 方法"POST">

在测试我的邮政方法时来自邮递员:

[HttpPost]
public Reservation AddReservation(string firstname, string lastname, string email, string cardnumber, string phonenumber)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
Reservation res = new Reservation()
{
FirstName = firstname,
LastName = lastname,
Email = email,
Cardnumber = cardnumber,
PhoneNumber = phonenumber
};
_context.Reservations.Add(res);
_context.SaveChanges();
return res;
}

如果我使 post 方法像这样获取对象:

[HttpPost]
public Reservation AddReservation(Reservation res)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
_context.Reservations.Add(res);
_context.SaveChanges();
return res;
}

然后我的POST方法工作正常,但在前端,我想传递参数,而不是模型类。

有人可以告诉我为什么会这样吗?

谢谢

我们需要将函数更改为

[HttpPost]
public IHttpActionResult AddReservation([FromBody] Reservation model)
{ 
_context.Reservations.Add(model);
_context.SaveChanges();
return Json(_context.Reservations.ToArray());
}

因为 POST 需要一个参数 - 查询字符串中的有效负载。如果没有这个参数,它正在寻找未定义的 Post(( 函数,我们得到错误 405

Reservation.cs
public class Reservation
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Cardnumber { get; set; }
public string PhoneNumber { get; set; }
}

相关内容

最新更新