调用 httpClient.PostAsync 将返回 null

本文关键字:返回 null PostAsync httpClient 调用 | 更新日期: 2023-09-27 18:34:22

我正在尝试调用实习生调用外部 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#有点陌生。

调用 httpClient.PostAsync 将返回 null

查看您在参数"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); } 
 });

分解代码,以便可以看到从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.