C# - Get Response from WebRequest and handle status codes

.net, c#

Solution

You have to check whether the response failed because of a server error (the WebException provides a WebResponse) or not. Maybe this will help you:

        HttpWebResponse response = null;

        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/thisisadeadlink");
            request.Method = "GET";

            response = (HttpWebResponse)request.GetResponse();

            StreamReader sr = new StreamReader(response.GetResponseStream());
            Console.Write(sr.ReadToEnd());
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                response = (HttpWebResponse)e.Response;
                Console.Write("Errorcode: {0}", (int)response.StatusCode);
            }
            else
            {
                Console.Write("Error: {0}", e.Status);
            }
        }
        finally
        {
            if (response != null)
            {
                response.Close();
            }
        }

Problem

I am writing an updatesystem for .NET-applications and at the moment I am stuck. I try to get a file on a remote server and its content. For that I want to use a HttpWebRequest to get the content and the status code if the operation fails. I built a function that contains a switch-query and each part asks the status code and does an action then. This looks like the following: ``` public void AskStatusCode(int code) { switch (code) { case 404: // Do an action break; case 405: // Do an action break; } } ``` Ok, that is it. Now I created a HttpWebRequest and a HttpWebResponse. ``` HttpWebRequest requestChangelog = (HttpWebRequest)HttpWebRequest.Create(url); requestChangelog.Method = "GET"; HttpWebResponse changelogResponse = (HttpWebResponse)requestChangelog.GetResponse(); // Now call the function and set the status code of the response as parameter. AskStatusCode((int)changelogResponse.StatusCode); ``` So, the theory should work, but it does not. It will not do any actions I put in the "case"-block for a special status code. I removed the file from the remote server to test if it will execute the case-block for code "404", but it always shows me an exception (remote server answered 404), but not that what I wanted this status code to handle with. So, my question is, why is this not working? The types are integers and I casted the status code to an Int32 as well, as you could see... To your info: After the status code had been checked and if it is ok, I want to read the content with a stream reader and the ResponseStream. Help would be appreciated. Excuse me, if you did not understand that, I tried to say it as clear as I could.

Original source