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

痴心易碎 提交于 2019-12-25 00:06:04

问题


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 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?


回答1:


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.



来源:https://stackoverflow.com/questions/4748963/data-sent-to-a-wcf-rest-service-wouldnt-go-to-the-stream-input-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!