我试图将JSON数据发布到web api,这两个项目都在我的本地计算机上运行。
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(@"http://localhost:53818/");
var result = client.PostAsync("api/values", new StringContent(data, Encoding.UTF8, "application/json")).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
}
此post方法中的接收值为NULL
public HttpResponseMessage Post([FromBody]string value)
{
return new HttpResponseMessage(HttpStatusCode.Created);
}
编辑----------- 所以我设法找出问题所在。我已经替换了这行代码
client.PostAsync("api/values", new StringContent(data, Encoding.UTF8, "application/json")).Result;
以下内容并且有效,如果有人发布解释,我将不胜感激
var response = client.PostAsJsonAsync("api/values", data).Result;
答案 0 :(得分:1)
这是因为WebApi不擅长从正文中序列化原始类型,当你发送'Content-Type'标题作为application / json时,框架试图使用set Json serializer序列化内容并且不是'能够,这就是你在变量中得到null的原因。
你可以
答案 1 :(得分:0)
因为您调用值,并且您的方法需要值。将您的调用更改为值或更改值的方法签名,在这种情况下更有意义