如何从 http 请求获取 HTTP 状态代码

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

我有以下代码,作为 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();
    }
}
c# httprequest
5个回答
8
投票

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

responseTask.Result.StatusCode

甚至更好

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

3
投票
  • 如果您已经在

    ContinueWith
    函数中,它有助于避免使用
    async
    ,因为您可以使用(更干净的)
    await
    关键字。

  • 如果您

    await
    SendAsync
    调用,您将获得一个
    HttpResponseMessage
    对象,您可以从以下位置获取状态代码:

  • 此外,将

    IDisposable
    对象包装在
    using()
    块中(
    HttpClient
    除外 - 应该是
    static
    单例或更好,使用
    IHttpClientFactory
    )。

  • 不要将

    HttpClient.DefaultRequestHeaders
    用于特定于请求的标头,而是使用
    HttpRequestMessage.Headers

  • Connection: Keep-alive
    标头将由
    HttpClientHandler
    自动为您发送。
  • 您确定需要在请求中发送
    Cache-control: no-cache
    吗?如果您使用 HTTPS,那么几乎可以保证不会有任何代理缓存导致任何问题 - 并且
    HttpClient
    也不使用 Windows Internet 缓存。
  • 不要使用
    Encoding.UTF8
    ,因为它添加了前导字节顺序标记。请改用私有
    UTF8Encoding
    实例。
  • 对于不在线程敏感上下文中运行的代码(例如 WinForms 和 WPF),请始终将
    .ConfigureAwait(false)
    与每个
    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 );
        }
    }
}

1
投票

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

https://learn.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
            );
        }
    }
}

0
投票

@AthanasiosKataras 对于返回状态代码本身是正确的,但如果您还想返回状态代码值(即 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;
}

0
投票

发生在我身上的是我忘记将

as
语句更改为正确的类型。例如:

//controller side - sending 202
return StatusCode((int)HttpStatusCode.Accepted, new GenericResultResponse<string>()
{
    Data,
    Message,
    Success = true
});

// test side - trying to convert to OkObjectResult
 var response = await _controller.myAction(It.IsAny<Request>()) as OkObjectResult;

更正测试

// test side
 var response = await _controller.myAction(It.IsAny<Request>()) as ObjectResult;
© www.soinside.com 2019 - 2024. All rights reserved.