Search code examples
c#jsonssishttpclient

C# HTTPClient Response Logging


I have the below code which I am using to send JSON data to an API using HTTPClient. I want to log the HTTP response/status code such as 200, 201, 400 etc. Please can someone assist me with how to log the response code?

Current code:

      public void Main()
        {
            //String filePath = @"your-path\test.json";
            String filepath = Dts.Variables["User::FileName"].Value.ToString();
            if (File.Exists(filepath))
            {
                try
                {
                    // Read the JSON file
                    string jsonData = File.ReadAllText(filepath);
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri("https://your-url.com");
                        var response = client.PostAsync("/url-path", new StringContent(jsonData, Encoding.UTF8, "application/json")).Result;
                        var responseContent = response.Content.ReadAsStringAsync();

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error reading or parsing the JSON file: {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine("The JSON file does not exist in the specified folder.");
            }
        }
    }

Solution

  • The PostAsync method returns a HttpResponseMessage which conatains IsSuccessStatusCode and the StatusCode property. If you use them your code will be like this :

    public void Main()
    {
        //String filePath = @"your-path\test.json";
        String filepath = Dts.Variables["User::FileName"].Value.ToString();
        if (File.Exists(filepath))
        {
            try
            {
                // Read the JSON file
                string jsonData = File.ReadAllText(filepath);
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://your-url.com");
                    var response = client.PostAsync("/url-path", new StringContent(jsonData, Encoding.UTF8, "application/json")).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine(response.StatusCode.ToString());
    
                        var responseContent = response.Content.ReadAsStringAsync();
                    }
    
    
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error reading or parsing the JSON file: {ex.Message}");
            }
        }
        else
        {
            Console.WriteLine("The JSON file does not exist in the specified folder.");
        }
    }
    }