C# HTTPClient 响应日志记录

问题描述 投票:0回答:2

我有以下代码,用于使用 HTTPClient 将 JSON 数据发送到 API。我想记录 HTTP 响应/状态代码,例如 200、201、400 等。请有人帮助我如何记录响应代码?

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.");
            }
        }
    }
c# json ssis httpclient
2个回答
0
投票

PostAsync 方法返回一个 HttpResponseMessage,其中包含 IsSuccessStatusCodeStatusCode 属性。 如果您使用它们,您的代码将如下所示:

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



   

0
投票

HttpClient.PostAsync
方法返回
HttpResponseMessage
对象,其中包含
StatusCode
属性和有关响应的其他附加信息。

因此,您可以使用以下字符串示例在执行后将其作为“StatusCode (StatusCodeDescription)”获取:

$"{(int)response.StatusCode} ({response.ReasonPhrase})"
(输出如
"200 (OK)"
500 (InternalServerError)
等):

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

但是,请求的执行也可能会抛出

HttpRequestException
(超时,作为最简单的例子)。而且,如果您在
HttpClient
块内同时声明
HttpResponseMessage
try
- 您无法在
response
块中获取
catch
信息。这就是为什么你应该在
try-catch
块中声明它:

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

另外,应该提到很多有关代码的内容,例如:

  • 不要在方法内部声明
    HttpClient
    以避免开销(参见 这个问题);
  • 不要在可等待的
    .Result
    上使用
    Task
    以避免死锁(请参阅这个问题);
  • 别忘了
    await
    你的
    Task
    。代码中的行
    responseContent = response.Content.ReadAsStringAsync()
    会将
    Task<string>
    对象存储在
    responseContent
    变量中,而不是您所期望的纯
    string
    。你应该
    await
    这个调用来获取字符串。

假设,我建议您仅在方法之外的某个地方声明和初始化

HttpClient
一次,然后重用它。还将您的方法标记为
async
以便能够等待
HttpClient
调用。简单的例子:

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();
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.