19

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.

2
  • Can you enter the debugger and see what the value of changelogResponse.StatusCode is? Commented Jan 3, 2014 at 17:02
  • The problem is that I am testing it all on another PC because on mine I do not have internet at the moment, so I tried to show the result in a MessageBox. This MessageBox is never shown, that means the exception already comes up when I try to create the HttpWebRequest. What should I do to get rid of that problem? A try-block seems not a good way to do this. Commented Jan 3, 2014 at 17:07

2 Answers 2

27

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();
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

It worked out for me, the response.StatusCode must be checked after throwing an exception, not before, like OP's code
6

StatusCodes in the range of 4xx and 5xx throw a WebException which is why the code is never reaching the switch statement.

You need to handle this exception in your code:

HttpWebRequest requestChangelog = null;
HttpWebResponse changelogResponse = null;

try
{
    requestChangelog = (HttpWebRequest)HttpWebRequest.Create(url);
    requestChangelog.Method = "GET";

    changelogResponse = (HttpWebResponse)requestChangelog.GetResponse();
}
catch (WebException we)
{
    //handle the error
}

AskStatusCode((int)changelogResponse.StatusCode);

If you are only interested in checking error status codes then you would move the AskStatusCode() call inside of the catch block.

11 Comments

Ok, so a try-block seems to help. I just found out what you said, but I was not sure how to catch the problem and if a try-block would be useful. I will try it and comment if it solved. Thanks!
@DGibbs,Why not call the AskStatusCode method in catch block. I think that's what OP trying to do.
@Rahul What if the status code returned is a 200 OK? Then AskStatusCode will never be called. I am assuming he wants to call it for all statuscodes and not just ones which throw an error.
@Rahul Exactly.... If the status code is a 200 OK, then the catch is never entered and AskStatusCode is never called (assuming it is moved to the catch block as you propose). If he needs to call AskStatusCode for non-error types, then it cannot be inside the catch block.
Try initialising the request/response to null instead of a new instance of each respective class
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.