C# HttpClient中的PostAsync没有';不要将数据发送到我的webapi
我创建了一个HttpClient实例,用post方法调用APIC# HttpClient中的PostAsync没有';不要将数据发送到我的webapi,c#,httpclient,webapi,C#,Httpclient,Webapi,我创建了一个HttpClient实例,用post方法调用API using (var client = new HttpClient()) { var person = new Stu(); person.ApplicantId = "48751889-D86E-487B-9508-000EAB65F11F";
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时,我收到的对象的applicationId为Null。
我不明白为什么applicationId为空
最后,我在API中将我的[FromForm]
更改为[FromBody]
,它工作正常,但仍停留在这一行var response=wait client.PostAsync(url,数据)代码>并且不会继续
等待键盘让我的应用程序卡住了,我这样做了
var response=wait client.PostAsync(url,数据).configurewait(false)代码>
但是我没有弄清楚它为什么会导致这个问题。如果您使用FromForm
属性,那么在发送POST消息时应该使用FormUrlEncodedContent
而不是StringContent
作为内容类型。如果您仍然想发送json,请在遇到断点时,将IsCoolegeStudent方法中的FromForm
更改为FromBody
。使用调试:windows:调用堆栈。然后你可以点击父方法来查看“s”的设置位置。我可以看到调用堆栈中调用的方法序列,对吗?对。家长之一未正确设置id。您应该能够单击父项并将鼠标悬停在变量上,以查看未正确设置id的位置。我已将其更改为FromForm,其工作正常,但它将停留在此行“var response=wait client.PostAsync(url,data);”您的服务器应用程序上仍然有断点吗?如果是-您的客户端正在等待服务器代码的执行。我删除了服务器上的所有断点,但在我调用我的服务时,它会在此行“var response=await client.PostAsync(url,data);”