[英]Calling a httpClient.PostAsync returns null
我試圖調用一個api,實習生調用外部API來獲取數據。 我寫的代碼是:
[HttpPost]
public IHttpActionResult Post()
{
string _endpoint = "https://someurl.com/api/v1/models?auth_token=mytoken";
var httpContext = (System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"];
string upload_id = httpContext.Request.Form["upload_id"];
string filename = httpContext.Request.Form["filename"];
string filesize = "1000";
//return this.Ok<string>(upload_id + " " + filename);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("upload_id", upload_id),
new KeyValuePair<string, string>("filename", filename),
new KeyValuePair<string, string>("filesize", filesize)
});
using (var httpClient = new HttpClient())
{
var response = httpClient.PostAsync(_endpoint, content).Result;
return Json(JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result));
}
}
客戶端然后我通過ajax進行調用以獲取數據:
$.ajax({
url: '/api/tws',
type: 'POST',
data: { 'file': "EX-IGES.IGS", 'upload_id': "eb550576d2" },
success: function (response) {
console.log('response',response);
}
});
但是它始終返回null。 我已經驗證了API調用工作,一切都正確。 我對C#有點新意。
打破代碼,這樣你就可以看到從PostAsync
返回的Task<T>
對象是什么。
var responseTask = httpClient.PostAsync(_endpoint, content);
var response = responseTask.Result;
// At this point you can query the properties of 'responseTask' to look for exceptions, etc.
查看您在參數“文件”中傳遞的ajax調用,但在C#中,您正在尋找“文件名”
修正了ajax代碼:
$.ajax({ url: '/api/tws',
type: 'POST',
data: { 'filename': "EX-IGES.IGS", 'upload_id': "eb550576d2" },
success: function (response) { console.log('response',response); }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.