Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Get Response from WebRequest and handle status codes

Tags:

c#

.net

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.

like image 795
Dominic B. Avatar asked Jan 03 '14 17:01

Dominic B.


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

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();
            }
        }
like image 158
Thunderbolt Avatar answered Sep 19 '22 12:09

Thunderbolt


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.

like image 35
DGibbs Avatar answered Sep 19 '22 12:09

DGibbs