0

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Science_Fiction
  • 3,403
  • 23
  • 27
  • You set the ContentType as `application/xml` but write a raw byte array not xml. – L.B Nov 18 '12 at 22:22
  • Sorry, that was out of desperation. I ended up getting all sorts of errors. I've edited the title and code slightly to reflect my first solution and error. – Science_Fiction Nov 18 '12 at 22:29

1 Answers1

3

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.

Hamish Smith
  • 8,153
  • 1
  • 34
  • 48
  • Thanks! Combination of both. Changed return type to Stream, no joy. Then did that and changed content type to application/octet-stream and it works. I should have maybe guessed this since before my service was accepting a base64 encoded version of the image and returning a Stream, this worked. It's when I introduced the byte [] in parameter that I got into trouble. – Science_Fiction Nov 18 '12 at 22:44