Getting a HttpStatusCode of 0
Asked Answered
U

10

35

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?

Unsay answered 14/1, 2016 at 17:22 Comment(0)
T
24

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.

Tamboura answered 14/1, 2016 at 17:38 Comment(2)
Also important to note that a 404 error will only occur if the request hits a valid web server. The web server creates the "404" status code.Burnell
Thank you, this was helpful.Unsay
S
24

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;
Smokejumper answered 3/8, 2018 at 18:31 Comment(0)
L
14

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.

Ludewig answered 7/1, 2019 at 22:27 Comment(2)
Perfect, this helped me a lot!Muldrow
It helped me figure out it was a certificate issue.Fourscore
L
4

You can try this on Windows Form:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Thank you @KJ3

Leontineleontyne answered 6/11, 2020 at 14:11 Comment(0)
C
0

In my case, I simply specified an invalid hostname.

Collazo answered 9/4, 2019 at 6:34 Comment(0)
N
0

In my case, using certificate authentication, the configured certificate was wrong. I hope this helps.

Newspaperwoman answered 8/7, 2020 at 12:51 Comment(0)
D
0

I get intermittent response 0 from server behind firewall. Following code has solved my problem

client.ConfigureWebRequest((r) =>
        {
          r.ServicePoint.Expect100Continue = false;
          r.KeepAlive = true;
        });
Delisadelisle answered 14/8, 2020 at 9:39 Comment(0)
G
0

If this line does not work

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

then try this

System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

this should work.

If I get StatusCode 0 issue during my post request then I use this two lines of code.

Germin answered 31/5, 2021 at 11:0 Comment(0)
M
0

The HttpStatusCode is set by the server/service that processes your HTTP requests. If you make a request that cannot be resolved to a valid server/service (bad URL, port, Security protocol, etc.), you simply cannot access the Http request processor that handles the request and there is no code that executes to set the HttpStatusCode - hence the default value of 0 for an integer type. If you are trying to catch this condition, make certain you catch the timeout exception on your Client Request (in the client code) and set the Httpcode to something that tells you what happened. I like HttpStatusCode 503 or 504 (Service Unavailable or Gateway Timeout) although the server can respond with those codes for other reasons so they are slightly ambiguous. Otherwise, just treat the Httpcode of 0 as a failure to reach the server/service for some network-related cause (again like no valid URL).

Mckale answered 4/7, 2021 at 10:45 Comment(0)
O
0

If you are using RestSharp, Method.Get request make sure you don't set Header "Content-Type": "application/json". Because RestSharp complained about Method.Get request cannot have any content in its request. Also, try set ThrowOnAnyError = true to see a more detailed error if there is any.

// Init Rest Client
var options = new RestClientOptions("https://SomeDomain.com")
{
    MaxTimeout = -1,
    RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true,
    ThrowOnAnyError = true
};
var client = new RestClient(options);
Onetoone answered 18/7, 2023 at 14:27 Comment(1)
Please post code as text and use the code formatting option. Screenshots of code are not allowed on StackOverflow. Please edit your answer and fix this. Also mind this in the future :)Decant

© 2022 - 2024 — McMap. All rights reserved.