Skip to main content
 首页 » 编程设计

c#之将 JSON 数据写入 HttpWebRequest 时收到 "Request was cancelled"错误

2024年02月13日31haluo1

我有一个使用 Monodevelop 用 C# 编写的 iOS 应用程序,作为应用程序的一部分,我调用了一个网络服务。 Web 服务调用要求将 JSON 数据写入请求。但是,我第一次尝试写入数据时收到错误消息;对具有相同参数的相同方法的所有后续调用都有效。以下是相关代码片段:

// Start snippet 
 
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (_connectionSettings.Uri); 
request.Timeout = 15000; // milliseconds 
if (_connectionSettings.Username != "") { 
    request.Credentials = new NetworkCredential (_connectionSettings.Username, _connectionSettings.Password); 
} 
 
if (post) { 
    request.Method = "POST"; 
    request.ContentType = "application/json"; 
    if (jsonData != null) { 
        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsonData); 
        request.ContentLength = byteArray.Length;     
        using (Stream ds = request.GetRequestStream()) {  //<--- ERROR HERE 
            ds.Write (byteArray, 0, byteArray.Length); 
        } 
    } else { 
        request.Method = "GET"; 
} 
 
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { 
 
// end snippet 

我得到的错误如下:

System.Net.WebException: Request was cancelled. ---> System.Exception: Cannot close the stream until all bytes are written --- End of inner exception stack trace --- at

System.Net.WebConnectionStream.Close () [0x00121] in

/Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:785 at System.IO.Stream.Dispose () [0x00000] in

/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.IO/Stream.cs:93 at

MyCustomMethod (System.String& responseString, System.String jsonData, Boolean post, Boolean suppressAlert) [0x00101] in /Path/To/My/Class.cs:192

知道我可能做错了什么吗?

编辑

好吧,显然在单步执行应用程序时,该方法每次都有效。我注意到,当抛出错误时,尽管 byteArray.Length 不为零,但 request.ContentLength 为零。但是,当单步执行应用程序时,request.ContentLength 保持 byteArray.Length 的预期值。

请您参考如下方法:

好的,看起来我们根本不需要设置 request.ContentLength。删除行:

request.ContentLength = byteArray.Length; 

完全解决了这个问题。我仍然很好奇这是否是库中的错误,因为大多数代码示例显示设置 HttpWebRequest 的 ContentLength,并且它在后续尝试中正常工作。