Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何解决;无法访问已处置的对象系统.net.HttpWebResponse“吗;?_C#_Httpwebrequest_Console Application_Httpwebresponse - Fatal编程技术网

C# 如何解决;无法访问已处置的对象系统.net.HttpWebResponse“吗;?

C# 如何解决;无法访问已处置的对象系统.net.HttpWebResponse“吗;?,c#,httpwebrequest,console-application,httpwebresponse,C#,Httpwebrequest,Console Application,Httpwebresponse,我有一个控制台应用程序,可以呼叫服务器。我意识到我没有将此应用到Station中,一旦我这样做了,我就会不断出现以下错误: “无法访问已释放的对象。\r\n对象名称: “System.Net.HttpWebResponse.” 在谷歌之后,我尝试了几次尝试,其中之一是: <system.net> <settings> <httpWebRequest useUnsafeHeaderParsing="true" /> </se

我有一个控制台应用程序,可以呼叫服务器。我意识到我没有将此应用到Station中,一旦我这样做了,我就会不断出现以下错误:

“无法访问已释放的对象。\r\n对象名称: “System.Net.HttpWebResponse.”

在谷歌之后,我尝试了几次尝试,其中之一是:

  <system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
  </system.net>
如何解决此问题?

您的
using(webResp…
会导致响应被放置在
using
语句的末尾括号中。之后访问响应将失败

最简单的解决方法是延迟处理
webResp
,直到您真正完成处理。您可以在方法receiving
webResp
中处理它

我想您应该使用类似以下内容的创建一个

using (HttpWebResponse x = CallServer(url))
{ }
HttpWebResponse webResp;
try
{
    webResp = (HttpWebResponse)request.GetResponse();
}
finally
{
    webResp.Dispose();
}
并删除
CallServer
方法中的
using

您的
using(webResp…
导致响应被放置在
using
语句的末尾括号中。之后访问响应将失败

最简单的解决方法是延迟处理
webResp
,直到您真正完成处理。您可以在方法receiving
webResp
中处理它

我想您应该使用类似以下内容的
创建一个

using (HttpWebResponse x = CallServer(url))
{ }
HttpWebResponse webResp;
try
{
    webResp = (HttpWebResponse)request.GetResponse();
}
finally
{
    webResp.Dispose();
}

并删除
CallServer
方法中的
using

编译器将
using
语句转换为如下内容:

using (HttpWebResponse x = CallServer(url))
{ }
HttpWebResponse webResp;
try
{
    webResp = (HttpWebResponse)request.GetResponse();
}
finally
{
    webResp.Dispose();
}
因此,如果要返回
webResp
并在方法之外使用此对象,则不能将其放入
using
语句中,因为
using
处置该对象。并且您不能使用已处置的对象(正如异常消息明确指出的那样)

您可能想使用
语句将对
CallServer
的调用包装在
中:

using (HttpWebResponse webResp = CallServer("http://..."))
{
   // do something with your response
}

编译器使用
语句将
转换为如下内容:

using (HttpWebResponse x = CallServer(url))
{ }
HttpWebResponse webResp;
try
{
    webResp = (HttpWebResponse)request.GetResponse();
}
finally
{
    webResp.Dispose();
}
因此,如果要返回
webResp
并在方法之外使用此对象,则不能将其放入
using
语句中,因为
using
处置该对象。并且您不能使用已处置的对象(正如异常消息明确指出的那样)

您可能想使用
语句将对
CallServer
的调用包装在
中:

using (HttpWebResponse webResp = CallServer("http://..."))
{
   // do something with your response
}