我正在尝试调用一个 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);
}
});
但是它总是返回空值。我已验证 API 调用有效并且一切正确。我对 C# 有点陌生。
最佳答案
查看您在参数"file"中传递的 ajax 调用,但在 C# 中您正在寻找“文件名”
固定ajax代码:
$.ajax({ url: '/api/tws',
type: 'POST',
data: { 'filename': "EX-IGES.IGS", 'upload_id': "eb550576d2" },
success: function (response) { console.log('response',response); }
});
关于c# - 调用 httpClient.PostAsync 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27517009/