skip to Main Content

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-pathtest.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.");
            }
        }
    }

2

Answers


  1. 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-pathtest.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.");
        }
    }
    }
    
    
    
       
    
    Login or Signup to reply.
  2. HttpClient.PostAsync method returns HttpResponseMessage object, which contains StatusCode property and other additional info about response.

    So, you can simply get it after execution as "StatusCode (StatusCodeDescription)" by using this string example: $"{(int)response.StatusCode} ({response.ReasonPhrase})" (outputs like 200 (OK), 500 (InternalServerError) etc):

    public void Main()
    {
        // ...
        using (var client = new HttpClient())
        {
            // ...
            var response = client.PostAsync(...).Result;
            // ...
            Console.WriteLine($"{(int)response.StatusCode} ({response.ReasonPhrase})"); 
            // ...
        }
    }
    

    BUT, execution of request may also throw an HttpRequestException (on timeout, as simplest example). And, in case you declare both HttpClient and HttpResponseMessage inside try-block – you can’t get response info in a catch-block. That’s why you should declare it out of try-catch blocks:

    public void Main()
    {
        // ...
        var client = new HttpClient();
        var response = (HttpResponseMessage?)null;
        // ...
        try
        {
            // ...
            response = client.PostAsync(...).Result;
            // ...
            Console.WriteLine($"{(int)response.StatusCode} ({response.ReasonPhrase})");
        }
        catch (Exception ex)
        {
            // Here you have access to response object, but don't forget null-checks
            Console.WriteLine($"{(int?)response?.StatusCode} ({response?.ReasonPhrase})");
        }
    }
    

    Also, should be mentioned lots of stuff about code, like:

    • don’t declare HttpClient inside method to avoid overhead (see this question);
    • don’t use .Result on awaitable Tasks to avoid deadlocks (see this question);
    • don’t forget to await your Tasks. Line from your code responseContent = response.Content.ReadAsStringAsync() will store Task<string> object inside responseContent variable, not pure string as you may expect. And you should await this call to get string.

    Assuming that, I recommend you to declare and initialize HttpClient only once, somewhere out of methods, and reuse it. Also mark your methods as async to be able to await HttpClient calls. In that way you get proper request calls, response handling and ability to log response. Simple example:

    private static readonly HttpClient _client = new() { BaseAddress = new Uri("SomeBaseUri") };
    
    public static async Task Main()
    {
        // ...
        var response = (HttpResponseMessage?)null;
        var responseContent = string.Empty;
        // ...
        try
        {
            // ...
            response = await _client.PostAsync(...);
            responseContent = await response.Content.ReadAsStringAsync();
            // ...
            Console.WriteLine($"Request executed with status: {(int)response.StatusCode} ({response.ReasonPhrase}). " +
                              $"Response body: {responseContent}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Request failed with status: {(int?)response?.StatusCode} ({response?.ReasonPhrase}). " + 
                              $"Error: {ex.Message}");
        }
    
        // If job with HttpClient done - don't forget to dispose it manually:
        _client.Dispose();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search