Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#异步GetWebRequest无法发布数据_C#_Asynchronous_Mono_Httpwebrequest_Streamwriter - Fatal编程技术网

C#异步GetWebRequest无法发布数据

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

我最近为我们的应用程序编写了一个异步HttpWebRequest客户端,它在.NET3.5中运行良好,但在Mono上,它无法在发送请求之前将数据正确写入请求

我已经确认了使用wireshark嗅探传出数据包的问题。HTTP请求已正确设置为POST,并带有JSON内容类型,但内容长度和数据为0

我目前有一个例外:

要写入的字节数大于指定的字节数 内容长度

我试图通过手动设置WebRequest的ContentLength并在将数据提供给流之前更改编码数据的方式来解决这个问题(我尝试了Steam和StreamWriter)

我还逐步完成了代码,并在异步方法中调试记录了变量,以确保数据确实存在。它似乎无法访问WebRequest对象

以下是相关代码:

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:这个修复了它!谢谢你,伙计。