我正在尝试调用一个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#有点新鲜。
答案 0 :(得分:2)
中断代码,以便查看Task<T>
返回的PostAsync
对象的内容。
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.
答案 1 :(得分:2)
查看您在参数“文件”中传递的ajax调用,但在C#中,您正在寻找“文件名”
修正了ajax代码:
$.ajax({ url: '/api/tws',
type: 'POST',
data: { 'filename': "EX-IGES.IGS", 'upload_id': "eb550576d2" },
success: function (response) { console.log('response',response); }
});