Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a httpClient.PostAsync returns null

Tags:

c#

.net

I am trying to make a call to an api that interns calls an external api for data. The code I have written is:

    [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));
        }



    }

Client side I am then making a call via ajax to get the data:

$.ajax({
        url: '/api/tws',
        type: 'POST',
        data: { 'file': "EX-IGES.IGS", 'upload_id': "eb550576d2" },
        success: function (response) { 
                 console.log('response',response);
                 }
 });

However it is always returning null. I have verified API call works and everything is correct. I a little new to C#.

like image 654
w3bMak3r Avatar asked Dec 29 '25 10:12

w3bMak3r


2 Answers

Look at the ajax call you are passing in the parameter "File" but in the C# you are looking for the "Filename"

Fixed ajax code:

$.ajax({ url: '/api/tws', 
       type: 'POST', 
       data: { 'filename': "EX-IGES.IGS", 'upload_id': "eb550576d2" }, 
       success: function (response) { console.log('response',response); } 
 });
like image 138
user2502479 Avatar answered Dec 31 '25 00:12

user2502479


Break the code up so you can see what The Task<T> object returned from PostAsync is saying.

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.
like image 36
Nick Strupat Avatar answered Dec 31 '25 01:12

Nick Strupat