c# - HttpClient 中的 PostAsync 不会将数据发送到我的 webapi
问题描述
我创建了一个 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; }
}
当我检查我的 API 时,我收到我的对象的申请者 ID 为空。
我不明白为什么ApplicantId 是空的。
最后,我在我的 API 中更改了我[FromForm]
的 to并且它工作正常,但它卡在这条线上并且没有继续。[FromBody]
var response = await client.PostAsync(url, data);
await 键盘使我的应用程序卡住了,我已经以这种方式对其进行了更改,
var response = await client.PostAsync(url, data).ConfigureAwait(false);
但我没有弄清楚为什么会导致此问题。
解决方案
如果您使用FromForm
属性,您应该在发送 POST 消息时使用FormUrlEncodedContent
而不是StringContent
作为内容类型。如果您仍想发送 json - 将FromForm
IsCoolegeStudent 方法更改为FromBody
.
推荐阅读
- ibm-midrange - 如何从 IFS 下载文本文件的最后一行删除 CRLF
- python - scipy.interpolate.SmoothSphereBivariateSpline 在示例数据上的行为不符合预期
- python - Celery+Rabbitmq 的公平任务处理顺序
- algorithm - 持续运行间隔调度算法的有效方法
- istio - 是否有可用的分布式多云服务网格解决方案?跨越 GCP、AWS、Azure 甚至本地设置的东西?
- python - 试图在熊猫中将数据框的某些列从浮点数转换为整数
- r - 如何计算R中数据框中的出现次数,而不重复
- javascript - 控制导航栏
- c# - 在 asp.net 核心的控制器中路由之前确定 URL
- angular - 在 Angular 中添加 formControlName 会破坏输入控件中的“值”