C#将文件上载到HTTPServer

C#将文件上载到HTTPServer,c#,http,C#,Http,我需要编写一个httpclient来使用http将一个巨大的文件上传到服务器。代码 public Stream function() { string postData = "This is a test that posts this string to a Web server."; byte[] byteArray = Encoding.UTF8.GetBytes (postData); // Set the ContentType property of the

我需要编写一个httpclient来使用http将一个巨大的文件上传到服务器。代码

public Stream function()
{
    string postData = "This is a test that posts this string to a Web server.";
    byte[] byteArray = Encoding.UTF8.GetBytes (postData);

    // Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded";

    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    request.Method = "POST";

    // Get the request stream.
    Stream dataStream = request.GetRequestStream ();

    // Write the data to the request stream.
    return dataStream;
}
然后,我将数据流返回给该函数的调用者,以便应用程序使用write继续写入流。然后,一旦完成写入,就会调用GetResponse,然后关闭流。但我有个例外

协议违反例外 写入流时在System.Net.HttpWriteStream.Write()处


请提供帮助。

由于请求方法是GET或HEAD,因此可能会抛出
ProtocolViolationException

必须将方法设置为如下所示的POST:

// Set the 'Method' property of the 'Webrequest' to 'POST'.
request.Method = "POST";

请参阅MSDN上的文档。

您是否考虑过在使用浏览器时使用来调试流程
这是一个简单的代理,允许您检查http流量。

您可以控制服务器吗。调试时,只需启动服务器检查抛出了哪些错误消息,就能获得巨大的帮助。@CodingBarfield的可能重复项:无法使用
application/x-www-form-urlencoded
上载文件。服务器可以创建文件,但由于数据不可用,因此会出现异常“由于线程退出或应用程序请求,I/O操作已中止“@jgauffin-您提到的链接不是我要查找的链接MSDN文档提到了在发布期间可能导致ProtocolViolationException的其他条件,如:KeepAlive为true,AllowWriteStreamBuffering为false,SendChunked为false。你查过了吗?另外,在调用GetResponse()之前是否关闭了请求流?是。已经检查了这些条件。您说您将请求流返回给此函数的调用者,以便应用程序继续写入流。您是否按照request.ContentLength中的设置将准确的字节数写入请求流?另外,在调用GetResponse()之前是否关闭了请求流?当sendChunked设置为false时,不需要设置字节数。另外,因为我将继续向流中写入,所以我不知道确切的字节数。好的,现在我也在学习一些新的东西。我从来没有真正研究过SendChunked做什么。我的点子快用完了。您是否使用诸如Fiddler之类的工具查看HTTP请求/响应实际发送的内容?