简体   繁体   English

在ASP.NET Core MVC中无法调用具有类参数带有[FromBody]属性的类的API Post方法

[英]Unable to call API Post Method that has a class parameter with [FromBody] attribute in asp.net core mvc

I am developing an API in asp.net core mvc for doing online reservations. 我正在asp.net核心mvc中开发API以进行在线预订。 But when I am trying to add a reservation from the API post method I am getting error: 但是,当我尝试从API post方法添加保留项时,出现错误:

WebException: The remote server returned an error: (415) Unsupported Media Type. WebException:远程服务器返回错误:(415)不支持的媒体类型。 System.Net.HttpWebRequest.GetResponse() System.Net.HttpWebRequest.GetResponse()

There are 2 projects: 有2个项目:

Project 1 项目1

There is a post method in my API action method that a [FromBody] attribute. 我的API操作方法中有一个[FromBody]属性的post方法。 I have to call this method and pass the reservation object. 我必须调用此方法并传递保留对象。

The method definition is : 方法定义为:

[HttpPost]
public Reservation Post([FromBody] Reservation res) =>
repository.AddReservation(new Reservation
{
    Name = res.Name,
    FromLocation = res.FromLocation,
    ToLocation = res.ToLocation
});

Project 2 In project 2 I want to call this API method. 项目2在项目2中,我想调用此API方法。 For that I have created a form in the view to fill name, from location and to location values. 为此,我在视图中创建了一个表单以填充名称(从位置到位置值)。 Then On the controller I have to call the API method (given above). 然后,在控制器上,我必须调用API方法(如上所述)。

The controller code is: 控制器代码为:

[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");
}

I am getting error - WebException: The remote server returned an error: (415) Unsupported Media Type. 我收到错误消息-WebException:远程服务器返回错误:(415)不支持的媒体类型。 System.Net.HttpWebRequest.GetResponse() System.Net.HttpWebRequest.GetResponse()

But when I am running powershell command then it works: 但是当我运行powershell命令时,它可以工作:

PM> Invoke-RestMethod http://localhost:8888/api/Reservation -Method POST -Body (@{Name="Anne"; ToLocation="Meeting Room 4"} | ConvertTo-Json) -ContentType "application/json"

Please help? 请帮忙?

In the former you're encoding the request body as x-www-form-urlencoded and in the latter as application/json . 在前者中,您将请求主体编码为x-www-form-urlencoded ,在后者中,将请求主体编码为application/json The same action cannot respond to both. 相同的动作不能同时响应两者。 Since the param is decorated with [FromBody] , application/json is the one you should be using, which is why the powershell command worked. 由于参数用[FromBody]装饰,因此application/json是您应该使用的参数,这就是powershell命令起作用的原因。

If you actually want x-www-form-urlencoded , then remove the [FromBody] attribute. 如果您实际上需要 x-www-form-urlencoded ,则删除[FromBody]属性。 If you actually need to support both, you'll need two separate routes: 如果您确实需要同时支持这两种方法,则需要两条单独的路线:

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);

There are two issues in your POST code, first I mentioned in comments and Chris in his answer. 您的POST代码中有两个问题,首先是我在评论中提到过,而Chris在他的回答中提到过。

Second one is how you generate your request's body, use something like this: 第二个是如何生成请求的正文,请使用类似以下的内容:

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();
}

code taken form this anwser 来自此答案的代码

Also you can use Json.Net to serialize your reservation(if all fields names and types match) 您也可以使用Json.Net序列化您的预订(如果所有字段名称和类型都匹配)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET CORE中将属性路由值转换为Model / FromBody参数 - Attribute Routing Values into Model/FromBody Parameter in ASP.NET CORE ASP.NET MVC 核心 - 将表单发布到 class 参数 - ASP.NET MVC Core - Post form to class parameter 在asp.net核心中调用asp.net mvc 5 Web api,FromBody始终为null - calling asp.net mvc 5 web api in asp.net core, FromBody always null 是否可以在 ASP.NET MVC [FromBody] 控制器方法参数中使用多态? - Is it possible to use polymorphism in and ASP.NET MVC [FromBody] controller method parameter? asp.net core webapi frombody 参数大小限制 - asp.net core webapi frombody parameter size limit FromBody 在 ASP.NET 核心 API 返回 null - FromBody in ASP.NET Core API returns null ASP.NET Core MVC添加的Edit()动作方法(POST)脚手架为什么ID参数传了两次? - Why is the ID parameter passed twice in the Edit() action method (POST) scaffold added by ASP.NET Core MVC? 从ASP.NET Core中的方法Attribute访问泛型类参数T. - Accessing generic class parameter T from a method Attribute in ASP.NET Core 与 ASP.NET Core 中的 FromBody 混淆 - Confused with FromBody in ASP.NET Core .net 核心控制器 - 是否向方法添加 [FromBody] 属性? - .net core controllers - Add [FromBody] attribute to method or not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM