[英]calling asp.net mvc 5 web api in asp.net core, FromBody always null
When I call the asp.net mvc 5 web api in Asp.net Core the input parameter FromBody always is null 当我在Asp.net Core中调用asp.net mvc 5 Web api时,输入参数FromBody始终为null
asp.net Mvc 6 web api asp.net Mvc 6 Web API
public void Post([FromBody]string id)
{
}
calling web api in asp.net core 在asp.net核心中调用Web API
using (var client = new HttpClient())
{
string stringData = JsonConvert.
SerializeObject("test");
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8,"application/json");
HttpResponseMessage response1 = client.PostAsync("http://localhost:49741/api/values/", contentData).Result;
}
As Crowcoder said. 正如Crowcoder所说。 You should register
MediaTypeFormatter
. 您应该注册
MediaTypeFormatter
。 Here simple arctile how do that provides to do what you want. 这里简单arctile 怎么做 ,它提供给你想要做什么。
But simpler is choose another way to work with incoming data. 但更简单的是选择另一种处理传入数据的方法。 As
application/json
. 作为
application/json
。 Create simple Dto class like: 创建简单的Dto类,例如:
public class TestDataDto
{
public string Id { get; set; }
}
And change argument type of your Post method: 并更改Post方法的参数类型:
// POST api/values
public void Post([FromBody]TestDataDto value)
{
}
Then code of your core client should be like this: 然后,核心客户的代码应如下所示:
static void Main(string[] args)
{
using (HttpClient httpClient = new HttpClient())
{
var someData = JsonConvert.SerializeObject(new { Id = "test" });
var content = new StringContent(someData, System.Text.Encoding.UTF8, "application/json");
var result = httpClient.PostAsync("http://localhost:55878/api/values", content).Result;
if (result.IsSuccessStatusCode)
{
Console.WriteLine("All is fine");
}
else
{
Console.WriteLine($"Something was wrong. HttpStatus: {result.StatusCode}");
}
}
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.