WCF 4.0 REST Upload MS-Excel File

2020-07-26 14:40发布

问题:

I am trying to upload MS-Excel file through WCF-REST Service. I used the solution given in below post:- RESTful WCF service image upload problem My POST Method is declared as:

  [OperationContract]
                [WebInvoke(Method = "POST", UriTemplate = "/RFQ")]
                [WebContentType("application/octet-stream")]
                void UploadRFQDoc(Stream fileContents);

When I debug, stream content is fine till the call goes, and when I attach service to debug, Stream fileContents parameter becomes null , and service returns with [Bad Request]. I am not sending large file (it is just 50 KB). I am using HttpClient to call the Post. Here are the client code(RestClient is HttpClient).

 protected void Post(string uri, Stream stream, int length)
        {
            var content = HttpContent.Create(output => CopyToStream(stream, output, length), "application/octet-stream", length);
            Uri relativeUri = new Uri(uri, UriKind.Relative);

            var resp = RestClient.Post(relativeUri, content);

            ProcessResponse(resp);
        }

        void CopyToStream(Stream input, Stream output, int length)
        {
            var buffer = new byte[length];
            var read = input.Read(buffer, 0, Convert.ToInt32 (length));

            output.Write(buffer, 0, read);
        }

Any clue what else can go wrong. Many Thanks.

回答1:

[WebContentType("application/octet-stream")] attribute was unnecessary here. I commented it out, and all worked fine :).