我正在 asp.net core mvc 中开发一个用于在线预订的 API。但是,当我尝试从 API 发布方法添加预订时,我收到错误消息:
WebException:远程服务器返回错误:(415)不支持的媒体类型。System.Net.HttpWebRequest.GetResponse()
有2个项目:
项目一
我的 API 操作方法中有一个 [FromBody] 属性的 post 方法。我必须调用此方法并传递预订对象。
方法定义是:
[HttpPost]
public Reservation Post([FromBody] Reservation res) =>
repository.AddReservation(new Reservation
{
Name = res.Name,
FromLocation = res.FromLocation,
ToLocation = res.ToLocation
});
项目 2 在项目 2 中,我想调用这个 API 方法。为此,我在视图中创建了一个表单来填写名称,从位置到位置值。然后在控制器上我必须调用 API 方法(如上所示)。
控制器代码为:
[HttpPost]
public IActionResult AddReservation(Reservation reservation)
{
HttpWebRequest apiRequest = WebRequest.Create("http://localhost:8888/api/Reservation") as HttpWebRequest;
apiRequest.Method = "Post";
string parameters = "Name=" + reservation.Name + "Image=" + reservation.Image + "&FromLocation=" + reservation.FromLocation + "&ToLocation=" + reservation.ToLocation;
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
apiRequest.ContentType = "application/x-www-form-urlencoded";
apiRequest.ContentLength = byteArray.Length;
// Add the post data to the web request
Stream postStream = apiRequest.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
string apiResponse = "";
using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
}
return RedirectToAction("Index");
}
我收到错误 - WebException:远程服务器返回错误:(415)不支持的媒体类型。System.Net.HttpWebRequest.GetResponse()
但是当我运行 powershell 命令时,它可以工作:
PM> Invoke-RestMethod http://localhost:8888/api/Reservation -Method POST -Body (@{Name="Anne"; ToLocation="Meeting Room 4"} | ConvertTo-Json) -ContentType "application/json"
请帮忙?
阿晨1998
慕的地8271018
相关分类