0

I'm trying to get the status code returned from http response, like this:

try
{
    HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
    string text

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
       text = responseStream.ReadToEnd();
    }

    var responseHeader = (HttpWebResponse)request.GetResponse();
    var status = responseHeader.StatusCode;
}
catch (WebException ex)
{
    MessageBox.Show(ex.ToString());
}

the problem is that I get this exception:

System.ObjectDisposedException : "Cannot access to removed object Name: 'System.Net.HttpWebResponse'."}

on this line: var status = responseHeader.StatusCode;

why happean this? I want get the status code and the description

2
  • One of the few exceptions where dispose is actually called too often :-) Commented Mar 1, 2016 at 14:59
  • 1
    You are missing a ';' after `string text' Commented Mar 1, 2016 at 15:02

1 Answer 1

3
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)

will dispose the response after leaving the using block.

So another call to (HttpWebResponse)request.GetResponse(); will throw the exception. Additionally, because it's a web response, you cannot read it twice.

Try this alternative:

HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
string text;

HttpStatusCode status;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
   text = responseStream.ReadToEnd();
   status = response.StatusCode;
}
Sign up to request clarification or add additional context in comments.

6 Comments

but if I want use the variable status also out the using? How can I do this?
You can bring the declaration outside the using statement just like you did with text. 'I'll update the answer but I am not sure of the return type.
uhm, okay but the HttpReturnStatus is underlined in red, no reference found
uhm, yes, as I said, I don't know the type ;-) , it's HttpStatusCode btw; msdn.microsoft.com/en-us/library/… I edited it.
|

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.