4

我在通过 RestSharp 将图像上传到我的服务器时遇到了一些问题。

我有一个接受 Stream 的 Rest Wcf 服务。如果我使用下面的代码,我总是会得到这个异常:

ProtocolViolationException 要写入流的字节超过指定的 Content-Length 字节大小。

我需要配置哪些设置...设置内容长度标头似乎没有什么区别。

服务器端不接收图像,而是一些较小的字节流。

任何帮助表示赞赏。

客户端(测试)代码:

byte[] byteArray = File.ReadAllBytes("small.jpg");
        request.AddHeader("Content-Length", int.MaxValue.ToString());//doesn't matter what length I put here
        request.AddFile("image/jpeg", (requestStream) =>
                                          {
                                              using (var ms = new MemoryStream(byteArray))
                                              {
                                                  ms.CopyTo(requestStream, byteArray.Length);//doesn't matter whether I add second param or not
                                                  ms.Flush();
                                                  ms.Close();
                                              }
                                          },
                        "sample",
                        "image/jpeg");


        request.Method = Method.POST;
        client.ExecuteAsync(request, (response, a) =>
        {
            Assert.IsNotNull(response.Content);
            string content = response.Content;
            resetEvent.Set();
        });

服务代码(返回存储图像的 URL)

[OperationContract]
    [WebInvoke(UriTemplate = "upload/{fileName}/{fileExtension}/{id}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    Message UploadPhoto(string fileName, String fileExtension, string id, Stream fileContents);
4

1 回答 1

3

Content-Length 标头是根据请求正文的内容自动设置的,因此您无需显式设置它。

于 2012-02-17T01:13:33.017 回答