System.ObjectDisposedException:'无法访问已处置的对象。'

时间:2017-08-16 08:48:13

标签: c# .net visual-studio .net-framework-version

这是我连接到不受信任的服务器的代码,但我总是得到这个错误我把代码放在using语句但它不工作返回空字符串 还尝试过看到这个问题的链接,但它没有工作

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;
    }

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:5)

在这一行:

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)

来自网站的引用:

  

using语句确保即使在对象上调用方法时发生异常,也会调用Dispose。您可以通过将对象放在try块中然后在finally块中调用Dispose来实现相同的结果;实际上,这就是编译器如何翻译using语句。

答案 2 :(得分:1)

看看这部分:

response

您在构建StreamReader时正在访问using,但这超出了您的using声明。 componentWillMount() { const script = document.createElement("script"); script.src = "https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"; script.async = true; script.onload = function() { // init your algolia code here } document.body.appendChild(script); }, 语句将处理响应,因此错误。