【问题标题】:RestSharp post image to WCF REST serviceRestSharp 将图像发布到 WCF REST 服务
【发布时间】:2012-03-03 11:57:16
【问题描述】:

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

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

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

我需要配置哪些设置...设置 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);

【问题讨论】:

    标签: .net rest restsharp


    【解决方案1】:

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

    【讨论】:

    • 嗯..所以文件可能太大了?
    • 您应该只使用接收字节数组的AddFile() 重载。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多