C#异步GetWebRequest无法发布数据
我最近为我们的应用程序编写了一个异步HttpWebRequest客户端,它在.NET3.5中运行良好,但在Mono上,它无法在发送请求之前将数据正确写入请求 我已经确认了使用wireshark嗅探传出数据包的问题。HTTP请求已正确设置为POST,并带有JSON内容类型,但内容长度和数据为0 我目前有一个例外: 要写入的字节数大于指定的字节数 内容长度 我试图通过手动设置WebRequest的ContentLength并在将数据提供给流之前更改编码数据的方式来解决这个问题(我尝试了Steam和StreamWriter) 我还逐步完成了代码,并在异步方法中调试记录了变量,以确保数据确实存在。它似乎无法访问WebRequest对象 以下是相关代码:C#异步GetWebRequest无法发布数据,c#,asynchronous,mono,httpwebrequest,streamwriter,C#,Asynchronous,Mono,Httpwebrequest,Streamwriter,我最近为我们的应用程序编写了一个异步HttpWebRequest客户端,它在.NET3.5中运行良好,但在Mono上,它无法在发送请求之前将数据正确写入请求 我已经确认了使用wireshark嗅探传出数据包的问题。HTTP请求已正确设置为POST,并带有JSON内容类型,但内容长度和数据为0 我目前有一个例外: 要写入的字节数大于指定的字节数 内容长度 我试图通过手动设置WebRequest的ContentLength并在将数据提供给流之前更改编码数据的方式来解决这个问题(我尝试了Steam和S
private void StartWebRequest(string payload) {
var httpWebRequest = (HttpWebRequest)WebRequest.Create(PortMapSleuthURL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null; // Setting this to null will save some time.
// start an asynchronous request:
httpWebRequest.BeginGetRequestStream(GetRequestStreamCallback, new object[] {httpWebRequest, payload});
try {
// Send the request and response callback:
httpWebRequest.BeginGetResponse(FinishPortTestWebRequest, httpWebRequest);
} catch (Exception e) {
Console.WriteLine(e.Message);
PortTestException();
}
}
private void GetRequestStreamCallback(IAsyncResult asyncResult) {
try {
object[] args = (object[])asyncResult.AsyncState;
string payload = (string)args[1];
HttpWebRequest request = (HttpWebRequest)args[0];
//StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(asyncResult), new UTF8Encoding(false));
StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(asyncResult), Encoding.UTF8);
// Write to the request stream.
streamWriter.Write(payload);
streamWriter.Flush();
streamWriter.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
PortTestException();
}
}
我认为您不应该在
EndGetRequestStream
之前调用BeginGetResponse
。也就是说,我会将其移动到GetRequestStreamCallback
中。这也是工作原理。mono和.NET之间的类似差异被认为是一个bug;您使用的是哪个版本的mono?它在Unity3D mono fork中运行。看起来它的Mono 2.12:这个修复了它!谢谢你,伙计。