System.ObjectDisposedException: 'Cannot access a disposed object.'

System.ObjectDisposedException: 'Cannot access a disposed object.'

这是我连接到不受信任的服务器的代码,但我总是收到此错误我将代码放在 using 语句中,但它不起作用 return 空字符串 之前也尝试过查看此问题的 link 但它不起作用

private String requestAndResponse(String url)
    {
        string responseValue = string.Empty;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = httpMethod.ToString();

        HttpWebResponse response = null;
        // for un trusted servers
        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        try
        {
            using (response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException("error code " + response.StatusCode.ToString());
                }
            }

            //process the response stream ..(json , html , etc..  )
            Encoding enc = System.Text.Encoding.GetEncoding(1252);
            StreamReader loResponseStream = new
                StreamReader(response.GetResponseStream(), enc);

            responseValue = loResponseStream.ReadToEnd();
            loResponseStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }



        return responseValue;
    }

第一个 using 块正在处理您的回复。将此块之后的代码移动到 using 语句中。

这一行:

StreamReader loResponseStream = new StreamReader(response.GetResponseStream(), enc);

您正在尝试访问 response,但此对象已被之前的 using 语句处理掉。

编辑:

此代码应该有效,处理所有对象并返回值:

using (HttpWebResponse  response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode != HttpStatusCode.OK)
    {
        throw new ApplicationException("error code " + response.StatusCode.ToString());
    }

    Encoding enc = System.Text.Encoding.GetEncoding(1252);

    using(StreamReader loResponseStream = new StreamReader(response.GetResponseStream(), enc))
    {
        return loResponseStream.ReadToEnd();
    }
}

允许从 using 语句返回,更多阅读:using Statement (C# Reference)

引自网站:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

看这部分:

using (response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode != HttpStatusCode.OK)
    {
        throw new ApplicationException("error code " +      response.StatusCode.ToString());
    }
 }

//process the response stream ..(json , html , etc..  )
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new
StreamReader(response.GetResponseStream(), enc);

您在构建 StreamReader 时正在访问 response,但这在您的 using 语句之外。 using 语句将处理响应,因此会出现错误。