Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. .Net Framework Web API & Client - Empty JSON

.Net Framework Web API & Client - Empty JSON

Scheduled Pinned Locked Moved Web Development
jsoncsharpdotnettestingbeta-testing
7 Posts 4 Posters 3 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Kevin Marois
    wrote on last edited by
    #1

    I have this API controller method

    [HttpGet]
    public HttpResponseMessage GetPersonList(int personTypeId = 0, int clientRepId = 0)
    {
    var response = new HttpResponseMessage();

    try
    {
        var data = Repository.GetPersonList(personTypeId, clientRepId);
                
        response = Request.CreateResponse(HttpStatusCode.OK, data);
    
        // AT THIS POINT THE RESPONSE HAS DATA&
    }
    catch (Exception e)
    {
        response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
    
    return response;
    

    }

    It's working and has data, and when I call it from Postman I can see the complete JSON. Here's my client:

    public class APIExecutor
    {
    private HttpClient _client;

    public APIExecutor(string baseAddress, HttpClient client = null)
    {
    if (client != null)
    {
    _client = client;
    }
    else
    {
    _client = new HttpClient();
    }

    \_client.BaseAddress = new Uri(baseAddress);
    \_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    

    }

    public async Task<T> GetAsync<T>(string action, Dictionary<string, dynamic> parameters)
    {
    T results = default(T);

    try
    {
        var queryString = CreateQueryString(action, parameters);
    
        HttpResponseMessage response = \_client.GetAsync(queryString).Result;
    
        // FOR TESTING - RETURNS EMPTY JSON \[\]
        var xxx = await response.Content.ReadAsStringAsync(); //<=== EMPTY JSON
    
        if (response.IsSuccessStatusCode)
        {
            // Status code is 200 here
            var responseString = await response.Content.ReadAsStringAsync();
    
            results = await ReadAsAsync<T>(response.Content);
        }
        else 
        {
            HandleException(response);
        }
    }
    catch (Exception e)
    {
        throw;
    }
    
    return results;
    

    }

    private async Task<T> ReadAsAsync<T>(HttpContent content)
    {
    var results = JsonConvert.DeserializeObject<T>(await content.ReadAsStringAsync());

    return results;
    

    }
    }

    Anyone see what's wrong? Thanks

    If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

    M Richard DeemingR 2 Replies Last reply
    0
    • K Kevin Marois

      I have this API controller method

      [HttpGet]
      public HttpResponseMessage GetPersonList(int personTypeId = 0, int clientRepId = 0)
      {
      var response = new HttpResponseMessage();

      try
      {
          var data = Repository.GetPersonList(personTypeId, clientRepId);
                  
          response = Request.CreateResponse(HttpStatusCode.OK, data);
      
          // AT THIS POINT THE RESPONSE HAS DATA&
      }
      catch (Exception e)
      {
          response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
      }
      
      return response;
      

      }

      It's working and has data, and when I call it from Postman I can see the complete JSON. Here's my client:

      public class APIExecutor
      {
      private HttpClient _client;

      public APIExecutor(string baseAddress, HttpClient client = null)
      {
      if (client != null)
      {
      _client = client;
      }
      else
      {
      _client = new HttpClient();
      }

      \_client.BaseAddress = new Uri(baseAddress);
      \_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      

      }

      public async Task<T> GetAsync<T>(string action, Dictionary<string, dynamic> parameters)
      {
      T results = default(T);

      try
      {
          var queryString = CreateQueryString(action, parameters);
      
          HttpResponseMessage response = \_client.GetAsync(queryString).Result;
      
          // FOR TESTING - RETURNS EMPTY JSON \[\]
          var xxx = await response.Content.ReadAsStringAsync(); //<=== EMPTY JSON
      
          if (response.IsSuccessStatusCode)
          {
              // Status code is 200 here
              var responseString = await response.Content.ReadAsStringAsync();
      
              results = await ReadAsAsync<T>(response.Content);
          }
          else 
          {
              HandleException(response);
          }
      }
      catch (Exception e)
      {
          throw;
      }
      
      return results;
      

      }

      private async Task<T> ReadAsAsync<T>(HttpContent content)
      {
      var results = JsonConvert.DeserializeObject<T>(await content.ReadAsStringAsync());

      return results;
      

      }
      }

      Anyone see what's wrong? Thanks

      If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

      M Offline
      M Offline
      Mycroft Holmes
      wrote on last edited by
      #2

      Just a guess - why dynamic and does ReadAsStringAsync deal with "dynamic" content?

      Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

      K 1 Reply Last reply
      0
      • M Mycroft Holmes

        Just a guess - why dynamic and does ReadAsStringAsync deal with "dynamic" content?

        Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

        K Offline
        K Offline
        Kevin Marois 2022
        wrote on last edited by
        #3

        The dictionary is parameters going to the controller and is working ok. The params make it to the controllwe. The problem is the JSON coming back is empty

        1 Reply Last reply
        0
        • K Kevin Marois

          I have this API controller method

          [HttpGet]
          public HttpResponseMessage GetPersonList(int personTypeId = 0, int clientRepId = 0)
          {
          var response = new HttpResponseMessage();

          try
          {
              var data = Repository.GetPersonList(personTypeId, clientRepId);
                      
              response = Request.CreateResponse(HttpStatusCode.OK, data);
          
              // AT THIS POINT THE RESPONSE HAS DATA&
          }
          catch (Exception e)
          {
              response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
          }
          
          return response;
          

          }

          It's working and has data, and when I call it from Postman I can see the complete JSON. Here's my client:

          public class APIExecutor
          {
          private HttpClient _client;

          public APIExecutor(string baseAddress, HttpClient client = null)
          {
          if (client != null)
          {
          _client = client;
          }
          else
          {
          _client = new HttpClient();
          }

          \_client.BaseAddress = new Uri(baseAddress);
          \_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          

          }

          public async Task<T> GetAsync<T>(string action, Dictionary<string, dynamic> parameters)
          {
          T results = default(T);

          try
          {
              var queryString = CreateQueryString(action, parameters);
          
              HttpResponseMessage response = \_client.GetAsync(queryString).Result;
          
              // FOR TESTING - RETURNS EMPTY JSON \[\]
              var xxx = await response.Content.ReadAsStringAsync(); //<=== EMPTY JSON
          
              if (response.IsSuccessStatusCode)
              {
                  // Status code is 200 here
                  var responseString = await response.Content.ReadAsStringAsync();
          
                  results = await ReadAsAsync<T>(response.Content);
              }
              else 
              {
                  HandleException(response);
              }
          }
          catch (Exception e)
          {
              throw;
          }
          
          return results;
          

          }

          private async Task<T> ReadAsAsync<T>(HttpContent content)
          {
          var results = JsonConvert.DeserializeObject<T>(await content.ReadAsStringAsync());

          return results;
          

          }
          }

          Anyone see what's wrong? Thanks

          If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

          Richard DeemingR Online
          Richard DeemingR Online
          Richard Deeming
          wrote on last edited by
          #4

          Kevin Marois wrote:

          public async Task<T> GetAsync<T>(string action, Dictionary<string, dynamic> parameters)
          {
          ...
          HttpResponseMessage response = _client.GetAsync(queryString).Result;

          Why? You're in an async method, so don't use the potentially deadlock-inducing .Result to synchronously get the result of a task. Just await the task.

          HttpResponseMessage response = await _client.GetAsync(queryString);

          Also, your controller can be simplified to:

          [HttpGet]
          public IEnumerable<Person> GetPersonList(int personTypeId = 0, int clientRepId = 0)
          {
          return Repository.GetPersonList(personTypeId, clientRepId);
          }

          If an unhandled exception is thrown, the framework will return an error response for you.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          K 1 Reply Last reply
          0
          • Richard DeemingR Richard Deeming

            Kevin Marois wrote:

            public async Task<T> GetAsync<T>(string action, Dictionary<string, dynamic> parameters)
            {
            ...
            HttpResponseMessage response = _client.GetAsync(queryString).Result;

            Why? You're in an async method, so don't use the potentially deadlock-inducing .Result to synchronously get the result of a task. Just await the task.

            HttpResponseMessage response = await _client.GetAsync(queryString);

            Also, your controller can be simplified to:

            [HttpGet]
            public IEnumerable<Person> GetPersonList(int personTypeId = 0, int clientRepId = 0)
            {
            return Repository.GetPersonList(personTypeId, clientRepId);
            }

            If an unhandled exception is thrown, the framework will return an error response for you.


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            K Offline
            K Offline
            Kevin Marois
            wrote on last edited by
            #5

            Thanks. I made the changes you suggested. However, I'm still not seeing any data coming back. The deserialZed JSON is empty, whereas the controller IS returning data. Any thoughts on what's causing this?

            If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

            Richard DeemingR 1 Reply Last reply
            0
            • K Kevin Marois

              Thanks. I made the changes you suggested. However, I'm still not seeing any data coming back. The deserialZed JSON is empty, whereas the controller IS returning data. Any thoughts on what's causing this?

              If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

              Richard DeemingR Online
              Richard DeemingR Online
              Richard Deeming
              wrote on last edited by
              #6

              A completely empty response, or an empty JSON array? If it's an empty JSON array, that would suggest your repository isn't returning any data. If it's a completely empty response, that would suggest a different problem. Either way, you'll probably need to compare the raw network request made by your code to the working one sent via Postman to see what's different.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              K 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                A completely empty response, or an empty JSON array? If it's an empty JSON array, that would suggest your repository isn't returning any data. If it's a completely empty response, that would suggest a different problem. Either way, you'll probably need to compare the raw network request made by your code to the working one sent via Postman to see what's different.


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                K Offline
                K Offline
                Kevin Marois
                wrote on last edited by
                #7

                I solved the issue. Thank you for your help. I'd like to post my finished class to get everyone's thoughts. I'd like your opinion on it. I'll post it later today

                If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups