c#:尝试使用httpwebrequest将文件发送到自托管web服务时出错
本文关键字:web 出错 服务 文件 httpwebrequest | 更新日期: 2023-09-27 18:11:06
首先,我的服务器是一个自托管的c# web服务。它在我的其他应用程序中工作得很好,但现在我必须在其中实现一个方法,该方法将由带有Windows CE 5的移动计算机使用。我需要在我的服务器上接收一个文件,所以我写了这个方法:
[System.ServiceModel.OperationContract, WebInvoke(UriTemplate = "test/")]
string testSaveFile(Stream arq);
public string testSaveFile(Stream img) {
Console.WriteLine("stream received");
Console.WriteLine("stream size: " + img.Length); //throws "Error 400 Bad Request"
}
在移动计算机上,我使用。net CF 3.5编写了这个方法来发送文件:
public static string UploadFilesToRemoteUrl( string url, string file ) {
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString( "x" );
HttpWebRequest httpWebRequest2 = ( HttpWebRequest ) WebRequest.Create( url );
httpWebRequest2.AllowWriteStreamBuffering = true;
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes( "'r'n--"
+ boundary + "'r'n" );
memStream.Write( boundarybytes, 0, boundarybytes.Length );
length += boundarybytes.Length;
string headerTemplate = "Content-Disposition: form-data; name='"file'";"
+" filename='"file'"'r'n Content-Type: '"application/octet-stream'"'r'n'r'n";
string header = headerTemplate;
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes( header );
memStream.Write( headerbytes, 0, headerbytes.Length );
length += headerbytes.Length;
FileStream fileStream = new FileStream( file, FileMode.Open,
FileAccess.Read );
byte[] buffer = new byte[1024];
int bytesRead = 0;
while( ( bytesRead = fileStream.Read( buffer, 0, buffer.Length ) ) != 0 ) {
memStream.Write( buffer, 0, bytesRead );
length += bytesRead;
}
memStream.Write( boundarybytes, 0, boundarybytes.Length );
length += boundarybytes.Length;
fileStream.Close();
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read( tempBuffer, 0, tempBuffer.Length );
memStream.Close();
requestStream.Write( tempBuffer, 0, tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
// ^ Exception here
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader( stream2 );
string res = reader2.ReadToEnd();
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
return res;
}
使用这种方法,我可以连接到服务器。它甚至显示第一条消息("收到的流")。但是每当我尝试访问流时,服务器都会返回"Error 400 Bad Request",这在移动计算机上显示为异常。那么,如何从移动计算机向服务器发送文件呢?我可以修复这种方法还是应该尝试另一种方法?
这个问题的答案说要异步执行,但我做了,并返回相同的错误,这个相同的服务器被Android应用程序使用,同步执行,它工作。
提前感谢。
还有一件事:multipart/form-data是发送文件到这个webmethod的正确方法吗?
问题不在发送部分。问题是读取流长度。这个问题的答案帮助了我。