尝试使用byte []输入

时间:2017-05-04 09:01:04

标签: c# rest post

我试过发布这么多不同的方式,但还没有进一步。我现在的解决方案返回以下错误消息:

  

传入的消息具有意外的消息格式“Raw”。该   操作的预期消息格式是'Xml'; 'Json的'。这个可以   是因为尚未配置WebContentTypeMapper   捆绑。有关更多信息,请参阅WebContentTypeMapper的文档   的信息。

RestService方法:

[WebInvoke(Method = "POST",ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "UploadUser/{sessionID}/{Name}")]
    [OperationContract(Name = "UploadUser")]
    string UploadUser(string sessionID, string name, byte[] image);

尝试发布到服务:

 client = new HttpClient();
 client.MaxResponseContentBufferSize = 256000;
 client.DefaultRequestHeaders.Clear();
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

 public async Task<string> SaveUserItemAsync(User item, bool isNewItem = false)
 {
     try
     {
         var RestUrl = "http://192.168.240.127:55642/RestServiceImpl.svc/UploadUser/{0}/{1}";

         var uri = new Uri(string.Format(RestUrl, item.Id, item.Name));

         var base64String = Convert.ToBase64String(item.Thumbnail, 0, item.Thumbnail.Length);
         var jsonStr = JsonConvert.SerializeObject(base64String);   
         var messageBytes = System.Text.Encoding.UTF8.GetBytes(jsonStr);     

         var cont = new ByteArrayContent(messageBytes);
         cont.Headers.ContentType= MediaTypeHeaderValue.Parse("text/plain");
         //also tried cont.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

         //also tried sending it as stringcontent
         //var json = JsonConvert.SerializeObject(item.Thumbnail);
         //var content = new StringContent(json, Encoding.UTF8, "application/json");              

         //also tried multipartcontent with no luck
         //var multipartContent = new MultipartFormDataContent();
         //multipartContent.Add(cont, "image");

         if (isNewItem)
         {

            var response = await client.PostAsync(uri, cont).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
               var res = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
               return res;
               Debug.WriteLine(@"User successfully saved.");

            }
        }

     }
     catch (Exception ex)
     {

     }
}

使用cont.Headers.ContentType = MediaTypeHeaderValue.Parse(“application / json”);

我得到另一个错误消息:

  

反序列化操作请求消息正文时出错   'UploadUser'。 OperationFormatter遇到无效的Message正文。   期望找到名称为“type”且值为“object”的属性。   找到值'string'。

Wireshark显示了这一点:

wireshark packet

更改了发送方式:

 var senderPackage = new Dictionary<string, byte[]>
                {
                    {"image", messageBytes}
                };               
                var json = JsonConvert.SerializeObject(senderPackage);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

出现新错误:

  

格式化程序在尝试反序列化时抛出异常   消息:尝试反序列化参数时出错   http://tempuri.org/:image。 InnerException消息是'有的   反序列化System.Byte []类型的对象时出错。结束元素   来自命名空间'''的'image'。找到文字   “Ii85ai80QUFRU2taSlJnQUJBUUFBQVFBQkFBRC8yd0JEQUJzU0ZCY1VFUnNYRmhjZUhCc2dLRUlyS0NVbEtGRTZQVEJDWUZWbFpGOVZYVnRxZUptQmFuR1FjMXRkaGJXR2tKNmpxNjJyWjRDOHlicW14NW1vcTZULzJ3QkRBUndlSGlnaktFNHJLMDZrYmwxdXBLU2twS1NrcEtTa3BLU2twS1NrcEtTa3BLU2twS ..

Wireshark数据包如下所示:

jsondictionarypic

如果有人知道如何让这个工作,我将永远负债;)

2 个答案:

答案 0 :(得分:0)

你应该使用&#34; application / json&#34;作为JSON请求标头中的媒体类型。

尝试:

  • cont.Headers.ContentType = MediaTypeHeaderValue.Parse(&#34; application / json&#34;);
  • RequestFormat = WebMessageFormat.Json到您的interface
  • 身体应该包含一个关键的图像&#39;值为字节列表。

     1. Make a dictionary with key "image" and with value array of bytes. 
     2. Serialize the dictionary to Json
     3. Use StringContent insead of ByteArray Content
    

答案 1 :(得分:0)

我最终通过创建自己的DataContract并将其作为流发送来使其工作。插入代码,任何人最终都会遇到同样的问题。

[DataContract]
    public class UploadObject
    {
        [DataMember(Name = "image")]
        public byte[] image { get; set; }

    }

休息服务方法:

  [OperationContract(Name = "UploadUser")]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "UploadUser/{sessionID}/{Name}")]
        string UploadUser(string sessionID, string name, Stream image);

张贴休息:

public async Task<string> SaveUserItemAsync(User item, bool isNewItem = false)
        {
            try
            {
                var RestUrl = "http://192.168.240.127:55642/RestServiceImpl.svc/UploadUser/{0}/{1}";

                var uri = new Uri(string.Format(RestUrl, item.Id, item.Name));
                UploadObject obj = new UploadObject();
                obj.image = item.Thumbnail;

                var json = JsonConvert.SerializeObject(obj);
                var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));

                var content = new StreamContent(stream);
                content.Headers.ContentLength = stream.Length;

                if (isNewItem)
                {

                    var response = await client.PostAsync(uri, content).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        var res = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        return res;                       
                    }

                    return "success";
                }

            }
            catch (Exception ex)
            {

            }
            return "Failure";
        }

几天后,服务开始抱怨它不能接受多个参数以及流输入,所以我将其更改为接收bytearray并设法通过创建我自己的jason来格式化bytearray这样:

 var json = "{ \"image\": [" + string.Join(",", item.Thumbnail) + "] }";

 var content = new StringContent(json);
 content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
 var response = await client.PostAsync(uri, content).ConfigureAwait(false);
相关问题