简体   繁体   English

C#:尝试使用httpwebrequest将文件发送到自托管Web服务时出错

[英]C#: error trying to send file to self-hosted webservice using httpwebrequest

First of all, my server is a self-hosted c# webservice. 首先,我的服务器是一个自托管的c#Web服务。 It works well for my other applications, but now I have to implement a method in it that will be used by a mobile computer with Windows CE 5. I will need to receive a file in my server, so I've written this method: 它可以很好地用于其他应用程序,但是现在我必须在其中实现一个方法,该方法将由具有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"
}

And in the mobile computer, using .Net CF 3.5 I've written this method to send the file: 在移动计算机中,使用.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;
}

And using this method I am able to connect to the server. 使用这种方法,我可以连接到服务器。 It even displays the first message ("stream received"). 它甚至显示第一条消息(“接收到的流”)。 But whenever I try to access the stream, the server returns "Error 400 Bad Request", which appears as an exception on the mobile computer. 但是,每当我尝试访问流时,服务器都会返回“错误400错误的请求”,该错误在移动计算机上显示为异常。 So how can I send a file from the mobile computer to the server? 那么如何将文件从移动计算机发送到服务器? Can I fix this method or should I try another approach? 我可以解决此方法还是应该尝试其他方法?

The answer to this question say to do it asynchronously but I did it and the same error is returned, and this same server is used by Android apps that do it synchronously and it works. 这个问题的答案说要异步执行,但是我做到了,并且返回了相同的错误,并且同步执行此操作的Android应用程序使用了该服务器,并且该服务器可以工作。

Thanks in advance. 提前致谢。

One other thing: is the multipart/form-data the correct approach to send files to this webmethod? 另一件事:multipart / form-data是将文件发送到此webmethod的正确方法吗?

The problem was not in the sending part. 问题不在发送方。 The problem was reading the stream lenghth. 问题在于读取流的长度。 The answer to this question helped me. 这个问题的答案帮助了我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM