HttpWebRequest 被取消 [英] HttpWebRequest was cancelled
问题描述
我正在使用 ASP.NET 读取 Request.InputStream 并将 HttpRequest 发送到发送给我的页面并抛出一个 QueryString 参数,我正确读取了 Request.InputStream 并正确地创建了 HttpRequest,但是当在我的Request.InputStream 我发现像Porsvägen"这样的特殊字符,我收到这个错误:ystem.Net.WebException:请求被中止:请求被取消.---> System.IO.IOException:在写入所有字节之前无法关闭流.在 System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)
I am using ASP.NET to read a Request.InputStream and send a HttpRequest to a page that was sent to me throw a QueryString parameter, I read correctly the Request.InputStream and I make the HttpRequest correctly, but when in my Request.InputStream I find special characters like this "Porsvägen" the I get this error: ystem.Net.WebException: The request was aborted: The request was canceled. ---> System.IO.IOException: Cannot close stream until all bytes are written. at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)
我获取 Request.InputStream 的代码是这样的:
My code for getting the Request.InputStream is this:
string requestData = (new StreamReader(Request.InputStream)).ReadToEnd();
我制作 HttpRequest 并发送它的代码是这样的:
My code for making a HttpRequest and sending it is this:
webRequest = (HttpWebRequest)WebRequest.Create(new Uri(urlDestination));
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = requestData.Length;
writer = new StreamWriter(webRequest.GetRequestStream());
writer.Write(requestData, 0, requestData.Length);//<-------Here I get the ERROR
if (writer != null)
{
writer.Close();
}
你能告诉我我的代码有什么问题吗,因为它可以工作,但是对于特殊字符它会崩溃.
Can you please tell me what is wrong with my code, because it works, but for special characters it crashes.
推荐答案
我已经通过实现这个来克服这个错误:
I have manage to overcome the error by implementing this:
string requestData = (new StreamReader(Request.InputStream)).ReadToEnd();
byte[] bytes = Request.ContentEncoding.GetBytes(requestData);
Stream writer = webRequest.GetRequestStream();
writer.Write(bytes, 0, bytes.Length);
我使用 Stream 来编写 HttpWebRequest
而不是 StreamWriter
并使用 ContentEncoding
以字节为单位读取 InputStream
I used Stream to write the HttpWebRequest
instead of StreamWriter
and read the InputStream
in bytes using the ContentEncoding
这篇关于HttpWebRequest 被取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!