获得HttpStatusCode为0

obi*_*ues 15 c# rest http http-status-codes http-status-code-404

如果我将客户端连接的服务指向错误的URL,为什么我得到的HttpStatusCode为0.

我的statusCodeAsInt显示为0.为什么它没有显示为404并正在处理?

IRestResponse response = client.Execute(restReq);
HttpStatusCode statusCode = response.StatusCode;

var statusCodeAsInt = (int) statusCode;

        if (statusCodeAsInt >= 500)
        {
            throw new InvalidOperationException("A server error occurred: " + response.ErrorMessage, response.ErrorException);
        }
        if (statusCodeAsInt >= 400)
        {
            throw new InvalidOperationException("Request could not be understood by the server: " + response.ErrorMessage,
                response.ErrorException);
        }
Run Code Online (Sandbox Code Playgroud)

处理此RestResponse的正确方法是什么?

小智 13

响应代码0通常意味着响应为空 - 即不返回标题.

这通常在接受连接时发生,然后正常关闭,也称为FIN连接.这是服务器声明已完成广播的地方,但会继续收听新消息.可能是防火墙问题.

另一件事是IRestResponse改为RestResponse.在这种情况下,使用IRestResponse没有任何优势.

  • 同样重要的是要注意,只有在请求到达有效的Web服务器时才会出现404错误.Web服务器创建"404"状态代码. (3认同)

KJ3*_*KJ3 11

在我的情况下,它不是导致StatusCode为0的防火墙问题.我们使用的是仍然在已阻止TLS 1.0连接的服务器上使用TLS 1.0的旧应用程序.一旦我们启用了TLS 1.2,我们就会得到我们期望的状态代码.

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)


Chr*_*wan 6

我认为状态码0表示没有状态码。这也可能意味着错误出在RestSharp中,而不是响应中。状态码为0时,甚至可能没有发送过请求。

检查是否有.ErrorException / .ErrorMessage。

  • 完美,这对我帮助很大! (3认同)