无法在asp.net核心mvc中调用具有[FromBody]属性的类参数的API Post方法

问题描述 投票:1回答:2

我正在使用asp.net core mvc开发一个用于在线预订的API。但是,当我尝试从API post方法添加预订时,我收到错误:

WebException:远程服务器返回错误:(415)不支持的媒体类型。 System.Net.HttpWebRequest.GetResponse()

有2个项目:

项目1

我的API动作方法中有一个post方法,即[FromBody]属性。我必须调用此方法并传递预留对象。

方法定义是:

[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"

请帮忙?

c# asp.net asp.net-mvc asp.net-core
2个回答
1
投票

您的POST代码中存在两个问题,首先我在评论中提到了Chris和他的回答。

第二个是你如何生成你的请求的主体,使用这样的东西:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{\"user\":\"test\"," +
                  "\"password\":\"bla\"}";

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

从这个anwser采取的代码

您也可以使用Json.Net序列化您的预订(如果所有字段名称和类型都匹配)


3
投票

在前者中,您将请求体编码为x-www-form-urlencoded,后者编码为application/json。同样的行动无法对两者做出回应。由于param用[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);
© www.soinside.com 2019 - 2024. All rights reserved.