开发者

Data sent to a WCF REST service wouldn't go to the Stream input parameter

I'm currently struggling with implementing file upload to a WCF REST service.

The client does the following:

void uploadFile( string serverUrl, string filePath )
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.
        Create( serverUrl );
    request.Method = "POST";
    request.ContentType = "multipart/form-data";
    request.SendChunked = true;
    request.Timeout = 60000;
    request.KeepAlive = true;

    using( BinaryReader reader = new BinaryReader( 
        File.OpenRead( filePath ) ) ) {

        request.ContentLength = reader.BaseStream.Length;
        using( Stream stream = request.GetRequestStream() ) {
            byte[] buffer = new byte[1024];
            while( true ) {
                int bytesRead = reader.Read( buffer, 0, buffer.Length );
                if( bytesRead == 0 ) {
                    break;
                }
                stream.Write( buffer, 0, bytesRead );
            }
        }
    }

     HttpWebResponse result = (HttpWebResponse)request.GetResponse();
     //handle result - not relevant
 }

where serverUrl is "http://localhost:/Service1.svc/UploadFile".

The WCF REST service has 开发者_JS百科a method with the following signature:

[OperationContract]
[WebInvoke(Method="POST")]
string UploadFile(System.IO.Stream fileData);

which is implemented as follows:

public string UploadFile(System.IO.Stream fileData)
{
    byte[] buffer = new byte[1024];
    while( true ) {
        int readAmount = fileData.Read( buffer, 0, buffer.Length );
        if( readAmount == 0 ) {
            break;
        }
    }
    return "";
}

When I start the service and run the client code the following happens.

The client starts the while-loop, control enters the service method and the server starts the while-loop. Read on the server returns zero, control falls through and the server method returns. Meanwhile the client gets an exception trying to call Write() - "Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host."

So to me it looks like the file data that I try to stream into the request just doesn't map onto the server method parameter. What am I doing wrong?


possibly try a different content-type? "application/octet-stream"

The code looks right to me. Does the client part read the entire file in or does it have problems? Test that first. Use fiddler to see what is actually going over the wire to the service.

If the client can read in the entire file to the buffer, try sending it all at once

request.Write(entireFileBuffer, 0, entireFileLength); request.close();

instead of chunking it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜