c# - HttpWebRequest 已取消

标签 c# asp.net xmlhttprequest

我正在使用 ASP.NET 读取 Request.InputStream 并将 HttpRequest 发送到发送给我的页面并抛出 QueryString 参数,我正确读取了 Request.InputStream 并且正确地创建了 HttpRequest,但是当在我的Request.InputStream 我发现像这样的特殊字符“Porsvägen”我得到这个错误: ystem.Net.WebException:请求被中止:请求被取消。 ---> System.IO.IOException:在写入所有字节之前无法关闭流。 在 System.Net.ConnectStream.CloseInternal( bool 内部调用, bool 中止)

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

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

最佳答案

我已经设法通过实现此错误来克服错误:

        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

关于c# - HttpWebRequest 已取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499006/

相关文章:

c# - 如何使用 NUnit Test 对 uwp 应用程序进行单元测试

c# - Entity Framework 创建与模型中每个类对应的单独数据库

asp.net - 授权与 Active Directory .NET Core 1.1、.Net Framework 的属性交互

c# - 防止 "Edit"用户控件上的 CSS 更改?

javascript - 使用 XMLHttpRequest 和 FileReader whyle 设置自定义内容类型和边界上传二进制文件

javascript - 实例化 XMLHttpRequest 对象的最佳方法

c# - 当原始查询使用 ORDER BY 子句时,LINQ .OrderBy().ThenBy() 运算符是否多余?

c# - C# 2 和 3 之间的区别

php - 使用 XmlHttpRequest 发出 DELETE 请求

c# - RabbitMQ - 知道哪条消息被确认