我是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}"
我对数据进行了硬编码,使其在动态化之前首先发挥作用。
我也试过使用await async方法,结果是一样的。 我在这里看到的所有问题和答案都不相似。
这是什么意思,我错了什么?
答案 0 :(得分:0)
您正在调用异步方法,但不等待它的结果。
变化:
var status = httpclient.PostAsJsonAsync("register", examp);
到
var status = await httpclient.PostAsJsonAsync("register", examp);
答案 1 :(得分:0)
扩展方法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;
}
答案 2 :(得分:0)
这是因为你没有等待这个电话,如
var status = await httpclient.PostAsJsonAsync("register", examp);
或者,使用ConfigureAwait()
var status = httpclient.PostAsJsonAsync("register", examp).ConfigureAwait(false);