Search code examples
c#asp.net-corehttp-headersdotnet-httpclienthttpresponsemessage

C# HttpClient GET returns 200 but an empty array


I've been trying to use HttpClient, to connect to an API. I'm able to send a GET request and recieve the desired data that I want from it through Postman and Fiddler, without issue.

The issue is that the json file i get from the HttpClient is: []

The HttpClient gives me the Status 200 while providing me with an empty array.

    public class CoolModel
    {
         public string name { get; set; }
         public int itemId{ get; set; }
         public string Devicename{ get; set; }
    }

var username = _config["Username"];
var password = _config[":Password"];
var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", username, password)));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
httpClient.DefaultRequestHeaders.Add("ApiKey", _config["ApiKey"]);
httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
httpClient.DefaultRequestHeaders.Add("User-Agent", "C# App");

HttpResponseMessage httpResponse = httpClient.GetAsync(_config["Url"] + $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}").Result;
       
var json = await httpResponse.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<List<CoolModel>>(json);

This will return the following: []

While what I want is:

[
    {
        "name":"John",
        "itemId":30,
        "Devicename":"something"
    }
]

My json that is returned is also []


Solution

  • My issue was that the Url

    var url = _config["Url"] + $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}"
    
    

    Contained empty new lines, so I had to remove the new lines. so I added the following to my url .Replace("\n", "").Replace("\r", ""));

    HttpResponseMessage httpResponse = await httpClient.GetAsync(url.Replace("\n", "").Replace("\r", ""));```