I’m having some trouble uploading images to my server via RestSharp.
I have a Rest Wcf service that accepts a Stream. If I use the code below I always get this Exception:
ProtocolViolationException Bytes to be written to the stream exceed
the Content-Length bytes size specified.
What settings to I need to configure… setting the content-length header seems to make no difference.
The server side doesn’t receive an image, but some smaller stream of bytes.
Any help appreciated.
Client (test) Code:
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();
});
Service Code (returns the Url of the stored image)
[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 header is set automatically based on the content of the request body so you don’t need to set it explicitly.