C#将JSON数据发布到REST API

jogvjijk  于 2023-03-04  发布在  C#
关注(0)|答案(3)|浏览(218)

我是REST API JSON的新手,但已经能够使用ASP.NET的一些API。以下是我目前面临的问题。
我已经能够使用此方法将JSON数据发送到API。

public void PostData()
{
    string sName = sysName.Text;
    string sDescrip = sysDescrip.Text;
    var httpclient = new HttpClient();
    httpclient.BaseAddress = new Uri("http://33.248.292.99:8094/bizzdesk/sysconfig/api/");
    var sys = new Bizsys(){name= sName, description= sDescrip};
    httpclient.PostAsJsonAsync("system", sys);
}

它工作正常。
现在我修改代码以容纳更多值,如下所示:

var httpclient = new HttpClient();
// ArrayList paramList = new ArrayList();
httpclient.BaseAddress = new Uri("http://179.683.197.115:9091/tua-slte/api/organisations/");
var org = new Organisation() { id=1, name = "inno", abbreviation = "abx", type="school", sort = 7, isShow = true, createdBy=8, createdDate = "10/04/2017", editedBy = 11, editDate="11/04/2017"};
var bas = new Basic() { id=1, username = "inno", password = "123", firstName="Innocent", lastName="Ujata", email = "ea@bizz.co", mobile = "123456", photo="10201001", loginIp="127.0.0.1", loginDate="10/04/2017", locked=false, organisation = org, createdDate = "10/04/2017", editedBy = 11, editDate="11/04/2017", admin=true};
var org2 = new Organisation2() { id=1, name = "inno", abbreviation = "abx", type="school", sort = 7, isShow = true, createdBy=17, createdDate = "10/04/2017", editedBy = 09, editDate="11/04/2017"};
var hq = new HeadQuarter() { zonId=09, organisation = org2, zonCode = "123", zonName = "Abuja", zonAddress = "123456", zonCity = "Abuja", zonPostalCode = "120076", zonEmail = "answers", zonPhoneNumber = "0908765", zonFaxNumber = "1212", zonState = "FCT", createdBy=17, createdDate = "10/04/2017", editedBy = 11, editDate="11/04/2017", version=1};
var examp = new RootObject() {basic=bas, headQuarter=hq  };

var status = httpclient.PostAsJsonAsync("register", examp);
return status;

它不断返回:

Id = 19, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

我对数据进行了硬编码,以便在使其动态化之前先看到其工作。
我也试过使用wait async方法,结果是一样的。我在这里看到的所有问题和答案都不相似。
这是什么意思,我错在哪里了?

7gs2gvoe

7gs2gvoe1#

您正在调用一个异步方法,但不等待它的结果。
变更:

var status = httpclient.PostAsJsonAsync("register", examp);

var status = await httpclient.PostAsJsonAsync("register", examp);
ljsrvy3e

ljsrvy3e2#

扩展方法PostAsJsonAsync返回Task<HttpResponseMessage>,抓取此任务,查看其详细信息,如果要返回请求完成的状态码,则应等待任务完成后,再从响应消息中抓取状态码:

private async Task<HttpStatusCode> PostSomethingAsync()
 {
     ...
     var response = await httpclient.PostAsJsonAsync("register", examp);
     return response.StatusCode;
 }

或者,您可以同步等待请求完成:

private HttpStatusCode PostSomething()
 {
     ...
     var response = httpclient.PostAsJsonAsync("register", examp).Result;
     return response.StatusCode;
 }
laximzn5

laximzn53#

那是因为你没有像

var status = await httpclient.PostAsJsonAsync("register", examp);

或者,使用ConfigureAwait()

var status = httpclient.PostAsJsonAsync("register", examp).ConfigureAwait(false);

相关问题