我在通过RestSharp将图像上传到服务器时遇到了一些问题。
我有一个接受流的Rest Wcf服务。如果我使用下面的代码,我总是会得到这个异常:
ProtocolViolationException要写入流的字节数超过指定的内容长度字节大小。
我需要配置哪些设置。。。设置内容长度标头似乎没有什么区别。
服务器端不接收图像,而是接收一些较小的字节流。
感谢您的帮助。
客户端(测试)代码:
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);
Content-Length头是根据请求体的内容自动设置的,因此不需要显式设置。