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
The PostAsync method returns a HttpResponseMessage which conatains IsSuccessStatusCode and the StatusCode property.
If you use them your code will be like this :
HttpClient.PostAsync
method returnsHttpResponseMessage
object, which containsStatusCode
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 like200 (OK)
,500 (InternalServerError)
etc):BUT, execution of request may also throw an
HttpRequestException
(on timeout, as simplest example). And, in case you declare bothHttpClient
andHttpResponseMessage
insidetry
-block – you can’t getresponse
info in acatch
-block. That’s why you should declare it out oftry-catch
blocks:Also, should be mentioned lots of stuff about code, like:
HttpClient
inside method to avoid overhead (see this question);.Result
on awaitableTask
s to avoid deadlocks (see this question);await
yourTask
s. Line from your coderesponseContent = response.Content.ReadAsStringAsync()
will storeTask<string>
object insideresponseContent
variable, not purestring
as you may expect. And you shouldawait
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 asasync
to be able to awaitHttpClient
calls. In that way you get proper request calls, response handling and ability to log response. Simple example: