C# - 如何从 http 请求中获取 HTTP 状态代码

C# - How to I get the HTTP Status Code from a http request

我有以下代码,作为 POST 请求按预期工作(给出正确的 URL 等)。似乎我在读取状态代码时遇到了问题(我收到了成功的 201,并且根据该数字我需要继续处理)。知道如何获取状态代码吗?

static async Task CreateConsentAsync(Uri HTTPaddress, ConsentHeaders cconsentHeaders, ConsentBody cconsent)
{
    HttpClient client = new HttpClient();

    try
    {
        client.BaseAddress = HTTPaddress;
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
        client.DefaultRequestHeaders.Add("Connection", "keep-alive");
        client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

        client.DefaultRequestHeaders.Add("otherHeader", myValue);
        //etc. more headers added, as needed...

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);

        request.Content = new StringContent(JsonConvert.SerializeObject(cconsent, Formatting.Indented), System.Text.Encoding.UTF8, "application/json");

        Console.WriteLine("\r\n" + "POST Request:\r\n" + client.DefaultRequestHeaders + "\r\nBody:\r\n" + JsonConvert.SerializeObject(cconsent, Formatting.Indented) + "\r\n");

        await client.SendAsync(request).ContinueWith
        (
            responseTask => 
            {
                Console.WriteLine("Response: {0}", responseTask.Result + "\r\nBody:\r\n" + responseTask.Result.Content.ReadAsStringAsync().Result);
            }
        );

        Console.ReadLine();
    }
    catch (Exception e)
    {
        Console.WriteLine("Error in " + e.TargetSite + "\r\n" + e.Message);
        Console.ReadLine();
    }
}

您的结果中有一个状态代码。

responseTask.Result.StatusCode

甚至更好

    var response = await client.SendAsync(request);
    var statusCode = response.StatusCode;
  • 如果您已经在 async 函数中,避免使用 ContinueWith 会有所帮助,因为您可以使用(更简洁的)await 关键字。

  • 如果您 await SendAsync 调用您将收到 HttpResponseMessage object 您可以从以下位置获取状态代码:

  • 此外,将您的 IDisposable object 包装在 using() 块中(HttpClient 除外 - 它应该是 static 单例或者更好,使用 IHttpClientFactory).

  • 不要在 request-specific header 中使用 HttpClient.DefaultRequestHeaders,请改用 HttpRequestMessage.Headers

  • Connection: Keep-alive header 将由 HttpClientHandler 自动为您发送。
  • 您确定要在请求中发送 Cache-control: no-cache 吗?如果您使用的是 HTTPS,那么几乎可以保证 proxy-caches 不会导致任何问题 - 而且 HttpClient 也不使用 Windows Internet 缓存。
  • 不要使用 Encoding.UTF8,因为它会添加前导 byte-order-mark。请改用私有 UTF8Encoding 实例。
  • Always use .ConfigureAwait(false) 在 thread-sensitive 上下文(例如 WinForms 和 WPF)中没有 运行 的代码上每个 await
private static readonly HttpClient _httpClient = new HttpClient();
private static readonly UTF8Encoding _utf8 = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true );

static async Task CreateConsentAsync( Uri uri, ConsentHeaders cconsentHeaders, ConsentBody cconsent )
{
    using( HttpRequestMessage req = new HttpRequestMessage( HttpMethod.Post, uri ) )
    {
        req.Headers.Accept.Add( new MediaTypeWithQualityHeaderValue("*/*") );
        req.Headers.Add("Cache-Control", "no-cache");
        req.Headers.Add("otherHeader", myValue);
        //etc. more headers added, as needed...

        String jsonObject = JsonConvert.SerializeObject( cconsent, Formatting.Indented );
        request.Content = new StringContent( jsonObject, _utf8, "application/json");

        using( HttpResponseMessage response = await _httpClient.SendAsync( request ).ConfigureAwait(false) )
        {
            Int32 responseHttpStatusCode = (Int32)response.StatusCode;
            Console.WriteLine( "Got response: HTTP status: {0} ({1})", response.StatusCode, responseHttpStatusCode );
        }
    }
}

您可以简单地检查响应的 StatusCode 属性:

https://docs.microsoft.com/en-us/previous-versions/visualstudio/hh159080(v=vs.118)?redirectedfrom=MSDN

static async void dotest(string url)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode.ToString());
        }
        else
        {
            // problems handling here
            Console.WriteLine(
                "Error occurred, the status code is: {0}", 
                response.StatusCode
            );
        }
    }
}

@AthanasiosKataras 对于 return 状态代码本身是正确的,但如果您还想 return 状态代码值(即 200、404)。您可以执行以下操作:

var response = await client.SendAsync(request);
int statusCode = (int)response.StatusCode

以上将为您提供 int 200。

编辑:

你没有理由不能做到以下几点吗?

using (HttpResponseMessage response = await client.SendAsync(request))
{
    // code
    int code = (int)response.StatusCode;
}