Restful service returns – 检查System.Byte 类型的对象的start元素时出错。 遇到意外的角色’ÿ’

所以我试图将图像从客户端发送到服务。

服务定义看起来像这样(实现没什么特别的,它没有到达那里,所以排除该代码):

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

调用客户端看起来像这样:

 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; 

它在最后一行抛出一个exception

远程服务器返回错误:(400)错误请求。

我已经尝试了所有可以考虑的事情:

request.ContentType

我正在做类似的事情(发布一个原始文件)我接受输入为Stream(不是byte [])。

此外,我希望请求的内容类型是application / octet-stream,尽管“application / json; charset = utf-8”可能会起作用。

当我测试它时,使用Stream作为输入参数类型或WebInvoke方法的返回值是获取请求/响应的原始主体的技巧。