I have a console app that makes calls to servers. I realized that I missed putting this into using statment and once I did that I kept getting this error:
"Cannot access a disposed object.\r\nObject name: 'System.Net.HttpWebResponse'."
After google I tried a few attempts, one of being:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
in the app.config
I still get the same error and I don't know why, my code:
public static HttpWebResponse CallServer(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
var webResp = (HttpWebResponse)null;
using (webResp = (HttpWebResponse)request.GetResponse())
{
}
return webResp;
}
How do I solve this?
Your using (webResp ...)
causes the response to be disposed at the end bracket of the using
statement. Accessing the response after that will fail.
The easy solution is to delay disposing of the webResp
until you are really done with it. You can dispose it in the method receiving webResp
.
I guess you should create a using
somewhat like this:
using (HttpWebResponse x = CallServer(url))
{ }
And remove the using
inside the CallServer
method.