【问题标题】:HttpWebRequest was cancelledHttpWebRequest 被取消
【发布时间】:2013-01-08 01:42:18
【问题描述】:

我正在使用 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)

我获取 Request.InputStream 的代码是这样的:

string requestData = (new StreamReader(Request.InputStream)).ReadToEnd();

我的 HttpRequest 和发送代码是这样的:

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

你能告诉我我的代码有什么问题吗,因为它可以工作,但是对于特殊字符它会崩溃。

【问题讨论】:

  • 什么类型的特殊字符导致代码崩溃/抛出异常?
  • ä 这是导致崩溃的字符,它们在 XML 中,例如包含此 ä 字符的 5673 长度 XML,并非所有字符都是特殊的,只有这 4 个。
  • The request was aborted 表示 Abort 在某个时候被请求调用。可能值得发布您的输入请求代码。

标签: c# asp.net xmlhttprequest


【解决方案1】:

我已经通过实现这个来克服错误:

        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

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多