尝试进行异步HttpWebRequest时有2个例外

时间:2013-10-02 19:56:34

标签: asp.net-mvc-4 asp.net-web-api system.net.httpwebrequest

我正在编写一个MVC Web API,make async HttpWebRequest调用。我有2个不同的例外。以下是我正在使用的方法。

第一个例外是:“此流不支持搜索操作。”它发生在responseStream上。

第二个例外是:“此流不支持超时”,这种情况发生在MemoryStream内容上。

我做错了什么?我一直在谷歌搜索,但没有找到任何解决方案。

谢谢,

朗达

enter image description here

enter image description here     private async Task GetHtmlContentAsync(string requestUri,string userAgent,string referrer,bool keepAlive,TimeSpan timeout,bool forceTimeoutWhileReading,string proxy,string requestMethod,string type)         {             //用于保存Response的字符串             string output = null;

        //create request object
        var request = (HttpWebRequest)WebRequest.Create(requestUri);
        var content = new MemoryStream();
        request.Method = requestMethod;
        request.KeepAlive = keepAlive;
        request.Headers.Set("Pragma", "no-cache");
        request.Timeout = (Int32)timeout.TotalMilliseconds;
        request.ReadWriteTimeout = (Int32)timeout.TotalMilliseconds;
        request.Referer = referrer;
        request.Proxy = new WebProxy(proxy);
        request.UserAgent = userAgent;

        try
        {
            using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        await responseStream.CopyToAsync(content);
                    }
                }

                var sr = new StreamReader(content);
                output = sr.ReadToEnd();
                sr.Close();
            }
        }
        catch (Exception ex)
        {
            output = string.Empty;
            var message = ("The API caused an exception in the " + type + ".\r\n " + requestUri + "\r\n" + ex);
            Logger.Write(message);
        }

        return output;
    }

1 个答案:

答案 0 :(得分:0)

我通过添加

解决了这个问题

content.Position = 0

在新的StreamReader线之前。现在我只需要使用GZip压缩就可以了。

朗达