[英]The PostAsync in HttpClient doesn't send data to my webapi
I've created a HttpClient instance to invoke an API with post method.我创建了一个 HttpClient 实例来使用 post 方法调用 API。
using (var client = new HttpClient())
{
var person = new Stu();
person.ApplicantId = "48751889-D86E-487B-9508-000EAB65F11F";
var json = JsonConvert.SerializeObject(person);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "http://localhost:52085/api/CollegeService/IsCoolegeStudent";
// var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
public class Stu
{
public string ApplicantId { get; set; }
}
When I check my API out , I receive ApplicantId of my object is Null.当我检查我的 API 时,我收到我的对象的申请者 ID 为空。
I cant not figure out why ApplicantId is Null.我不明白为什么申请人 ID 是空的。
Finally I've changed my [FromForm]
to [FromBody]
in my API and it worked correctly but it stuck on this line var response = await client.PostAsync(url, data);
最后,我在我的 API
[FromBody]
[FromForm]
更改为[FromBody]
并且它工作正常但它停留在这一行var response = await client.PostAsync(url, data);
and doesn't go on.并没有继续。
the await keyboard make my app stuck ,I've changed it this way var response = await client.PostAsync(url, data).ConfigureAwait(false);
等待键盘让我的应用程序卡住了,我已经改变了这种方式
var response = await client.PostAsync(url, data).ConfigureAwait(false);
but I didn't figure it out why it cause this problem.但我不明白为什么会导致这个问题。
If you using FromForm
attribute, you should use FormUrlEncodedContent
instead of StringContent
as content type when you send POST message.如果使用
FromForm
属性,则在发送 POST 消息时应使用FormUrlEncodedContent
而不是StringContent
作为内容类型。 If you still want send json - change FromForm
at IsCoolegeStudent method to FromBody
.如果你仍然想发送JSON -改变
FromForm
在IsCoolegeStudent方法FromBody
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.