Search code examples
c#.netwcfexceptionwcf-rest

Restful service returns - There was an error checking start element of object of type System.Byte[]. Encountered unexpected character 'ÿ'


So I am trying to send an image from the client side to the service.

Service definition looks like this (implementation is nothing fancy and It doesn't reach there so excluding that code):

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "Image")]
Stream Image(byte [] Image);

The calling client looks like this:

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

string uri = "http://localhost:8000/RestfulService/Image";

Bitmap img = new Bitmap("Random.jpg");
byte[] byteArray = ImageToByte(img);

var request = WebRequest.Create(uri) as HttpWebRequest;

if (request != null)
{
    request.ContentType = "application/json";
    request.Method = "POST";
}

if (request.Method == "POST")
{
    request.ContentLength = byteArray.Length;
    Stream postStream = request.GetRequestStream();
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();
}

if (request != null)
{
    var response = request.GetResponse() as HttpWebResponse;

It throws an exception at the last line with

The remote server returned an error: (400) Bad Request.

I've tried all possible things I can think of for:

request.ContentType


Solution

  • Where I am doing something similar (posting a raw file) I accept the input as a Stream (not byte[]).

    Also I would expect the content type of the request to be application/octet-stream although "application/json; charset=utf-8" would probably work.

    When I was testing this, using Stream as the input parameter type or return value of the WebInvoke method was the trick to get the raw body of the request / response.