Problem is HttpClient

Jassim Al Rahma 1,551 Reputation points
2022-11-04T09:22:03.543+00:00

Hi,

I have the below code that I am 100% sure about the URL and I am also verifying the PackageID when I Breakpoint.

But the problem is the result is always zero rows although when I use the same URL in Postman Ia m getting the correct output

What could be the reason please?

using (httpClient = new HttpClient())  
{  
    httpClient.BaseAddress = new Uri("https://www.jassimalrahma.com/package.php");  
  
    var content = new FormUrlEncodedContent(new[]  
    {  
        new KeyValuePair<string, string>("package", PackageID),  
    });  
  
    var response = await httpClient.PostAsync("https://www.jassimalrahma.com/package.php", content);  
  
    var result = await response.Content.ReadAsStringAsync();  
  
    List<PackageDetailsData> data = JsonSerializer.Deserialize<List<PackageDetailsData>>(result);  
  
    LabelPackageName.Text = data[0].package_name;  
}  

Here is my Postman:

257277-screenshot-2022-11-04-at-62558-pm.png

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,630 questions
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,496 Reputation points
    2022-11-04T09:31:40.467+00:00

    It's likely that you're reading the body of a bad response. Under your var response = ... like try adding this:

       response.EnsureSuccessStatusCode();  
    

    My bet is the request was a 300 range status code (redirect). If that's the case you check the response.Headers.Location property to see where the server is trying to redirect you.


  2. Bruce (SqlWork.com) 61,266 Reputation points
    2022-11-04T15:44:37.487+00:00

    you are probably send a bad id. the following code works:

    using System.Net.Http;  
    using System.Text.Json;  
      
    var PackageID = "2";  
    using (var httpClient = new HttpClient())  
    {  
        httpClient.BaseAddress = new Uri("https://www.jassimalrahma.com/package.php");  
        var content = new FormUrlEncodedContent(new[]  
        {  
             new KeyValuePair<string, string>("package", PackageID),  
        });  
      
        var response = await httpClient.PostAsync("https://www.jassimalrahma.com/package.php", content);  
      
        var result = await response.Content.ReadAsStringAsync();  
      
        List<PackageDetailsData> data = JsonSerializer.Deserialize<List<PackageDetailsData>>(result);  
      
        Console.WriteLine(data[0].package_name);  
    }  
      
      
    public class PackageDetailsData  
    {  
        public int package_id { get; set; }  
        public string? package_uuid { get; set; }  
        public string? package_name { get; set; }  
    }