Issues with HTTPClient returning null response with async

I've been trying to get a JSON response from a server through php. I can confirm that the uri correctly returns the JSON string I'm looking for so it's not an issue on that end. Also, this is only an issue with async request and a regular HTTP request call returns the correct JSON string.

Here is my async method:
public async Task<List> getUserInfoAsync(string username)
{

        var client = new System.Net.Http.HttpClient();

        client.BaseAddress = new Uri(address); // address is of form "http://www.something.com/"

        var response = await client.GetAsync(phpScript + username);  // phpScript is of form "php?username=" with 'username' being the requested username to grab from the database

        var userJson = response.Content.ReadAsStringAsync().Result;

        var rootObject = JsonConvert.DeserializeObject<userRoot>(userJson);

        return rootObject.user;
    }

So the 'response' variable ends up null which in turn causes userJson and rootObject.users to be null as well. I can't seem to figure out what is going wrong with the code. Any tips? Thanks!

Answers

  • TorbenKruseTorbenKruse DEMember ✭✭✭
    edited July 2015

    var userJson = await response.Content.ReadAsStringAsync();

    Edit: You should probably also check your response for IsSuccessStatusCode

  • NMackayNMackay GBInsider, University mod

    @FilipTodorovic

    Seems okay, here's some async code of mine for comparison.

    `
    public async Task<IList> GetCustomers(string token, string srch, CancellationToken ct)
    {
    using (var client = new HttpClient())
    {
    var url = string.Format(_endpoint + "GetCustomers");
    var package = JsonConvert.SerializeObject(srch);

                HttpContent content = new StringContent(package, Encoding.UTF8, WebConstants.ContentTypeJson);
                content.Headers.Add(_header, token);
    
                var resp = await client.PostAsync(url, content, ct);
    
                if (resp.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new SecurityException(WebConstants.ServiceSecWarning, new Exception(resp.Content.ToString()));
                }
    
                var result = JsonConvert.DeserializeObject<IList<CustomerPreview>>(resp.Content.ReadAsStringAsync().Result);
                return result;
            }
        }
    

    `

  • VolodymyrSavchenkoVolodymyrSavchenko UAMember ✭✭✭

    I have now same problem. As can i suggest this is because of proxy.

  • I had the same problem, here is the solution.

    var stream = response.Content.ReadAsStreamAsync().Result;
    StreamReader reader = new StreamReader(stream);
    string text = reader.ReadToEnd();

    string content = text;
    string des = JsonConvert.DeserializeObject(content);

  • RonaldBaayenRonaldBaayen CAMember ✭✭

    I am currently facing same issue, it was initially working and now its not. with Async I was getting data, my web services are running and can hit debug when I call api from browser. I checked my Android app and do have Internet permission. Wonder who is culprit in code for giving null response and raising exception!!

    Any Idea?

  • JerinJohnKJerinJohnK INMember

    Was facing the same problem adding this config file from this blog magically fixed the issue.

    Add an app.config with the the following content:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
       <runtime>
          <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
             <dependentAssembly>
                <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="2.0.5.0" />
             </dependentAssembly>
    
          </assemblyBinding>
       </runtime>
    </configuration>
    
  • sudhir.9350sudhir.9350 INUniversity ✭✭

    @RonaldBaayen - I have same problem. Have you find any solutions?

  • DarshanJSDarshanJS USMember ✭✭✭✭

    @RonaldBaayen said:
    I am currently facing same issue, it was initially working and now its not. with Async I was getting data, my web services are running and can hit debug when I call api from browser. I checked my Android app and do have Internet permission. Wonder who is culprit in code for giving null response and raising exception!!

    Any Idea?

    Bro i have same issue now how did you solved this issue

  • doxsidoxsi Member
    edited September 2018
        Try setting    DefaultRequestHeaders on the response type like:
    

    client.DefaultRequestHeaders.Add("Accept", "application/json");

  • KiritKirit Member
    edited March 18
    await Httpclient.GetAsync("url") doesn't work with mobile Internet. But when I am connected to better WiFi it works and It returns response as required.

    I am using xamarin form, with asp. Net Web core api published to azure.

    Does anyone know the answer to this.

    Please help
  • RHudsonRHudson CAMember ✭✭✭

    Are you calling a server with a self-signed certificate?

    Try adding this:

    System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
    
    
  • @RonaldBaayen @DarshanJS @Kirit where you able to find the solution for it?

    HttpResponseMessage response = await client.SendAsync(message);
    string responseString = await response.Content.ReadAsStringAsync();

    I'm trying to pass this but it comes as null response and gives an exception.
    I am using xamarin forms, with asp. Net Web api published to azure.

Sign In or Register to comment.