繁体   English   中英

调用httpClient.PostAsync会返回null

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM