Getting a HttpStatusCode of 0

2019-06-15 09:05发布

Why am I getting a HttpStatusCode of 0 if I point the service my client is connecting to to a bad URL.

My statusCodeAsInt is showing up as a 0. Why is it not showing up as a 404 and being handled?

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

What is the proper way to handle this RestResponse?

4条回答
Deceive 欺骗
2楼-- · 2019-06-15 09:28

A response code of 0 generally means that the response was empty - i.e. not even headers were returned.

This usually happens when a connection is accepted, and then closed gracefully, also known as a FIN connection. Which is where the server states that it has finished broadcasting to you, but will continue to listen for new messages. Could be a firewall issue.

Another thing to do is to change IRestResponse to RestResponse. Using IRestResponse offers no advantages in this scenario.

查看更多
Viruses.
3楼-- · 2019-06-15 09:30

In my case it was not a firewall issue causing the StatusCode of 0. We were using a legacy app that was still using TLS 1.0 on a server that had blocked TLS 1.0 connections. Once we enabled TLS 1.2, we got the status codes we were expecting.

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
查看更多
我想做一个坏孩纸
4楼-- · 2019-06-15 09:34

In my case, I simply specified an invalid hostname.

查看更多
萌系小妹纸
5楼-- · 2019-06-15 09:42

I think the statuscode of 0 means there is no status code. It can also mean the error was in RestSharp, not the response. With a statuscode of 0, the request may not have even been sent.

Check for an for a .ErrorException / .ErrorMessage.

查看更多
登录 后发表回答