我正在 asp.net core mvc 中开发一个用于在线预订的 API。但是当我尝试通过 API post 方法添加预订时出现错误:
WebException: The remote server returned an error: (415) Unsupported Media Type. System.Net.HttpWebRequest.GetResponse()
有2个项目:
项目 1
在我的 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 方法。为此,我在 View 中创建了一个表单来填写名称、位置和位置值。然后在 Controller 上我必须调用 API 方法(上面给出)。
Controller 代码是:
[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"
请帮忙?
最佳答案
在前者中,您将请求主体编码为 x-www-form-urlencoded
,在后者中编码为 application/json
。同一个 Action 不能同时响应两者。由于参数用 [FromBody]
修饰,application/json
是您应该使用的参数,这就是 powershell 命令起作用的原因。
如果您确实想要 x-www-form-urlencoded
,请删除[FromBody]
属性。如果您确实需要同时支持两者,则需要两条单独的路线:
private Reservation PostCore(Reservation res)
{
// do something
}
[HttpPost("json")]
public Reservation PostJson([FromBody] Reservation res) => PostCore(res);
[HttpPost("")]
public Reservation PostForm(Reservation res) => PostCore(res);
关于c# - 无法在asp.net core mvc中调用具有带有[FromBody]属性的类参数的API Post方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52319669/