C# 尝试使用字节[]输入发布到rest服务时请求错误

C# 尝试使用字节[]输入发布到rest服务时请求错误,c#,rest,post,C#,Rest,Post,我尝试过很多不同的方法,但都没有进一步的进展。我现在所在的解决方案返回以下错误消息: 传入消息具有意外的消息格式“Raw”。这个 操作的预期消息格式为“Xml”;“Json’。这个可以 可能是因为尚未在上配置WebContentTypeMapper 结合有关更多信息,请参阅WebContentTypeMapper的文档 细节 RestService方法: [WebInvoke(Method = "POST",ResponseFormat = WebMessageFormat.Json, Body

我尝试过很多不同的方法,但都没有进一步的进展。我现在所在的解决方案返回以下错误消息:

传入消息具有意外的消息格式“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)
     {

     }
}
client=newhttpclient();
client.MaxResponseContentBufferSize=256000;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/xml”);
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“text/html”);
公共异步任务SaveUserItemAsync(用户项,bool isNewItem=false)
{
尝试
{
var RestUrl=”http://192.168.240.127:55642/RestServiceImpl.svc/UploadUser/{0}/{1}";
var uri=新的uri(string.Format(RestUrl,item.Id,item.Name));
var base64String=Convert.ToBase64String(item.thumboil,0,item.thumboil.Length);
var jsonStr=JsonConvert.SerializeObject(base64String);
var messageBytes=System.Text.Encoding.UTF8.GetBytes(jsonStr);
var cont=新的ByteArrayContent(messageBytes);
cont.Headers.ContentType=MediaTypeHeaderValue.Parse(“文本/普通”);
//还尝试了cont.Headers.ContentType=MediaTypeHeaderValue.Parse(“应用程序/json”);
//还尝试将其作为stringcontent发送
//var json=JsonConvert.SerializeObject(item.缩略图);
//var content=newstringcontent(json,Encoding.UTF8,“application/json”);
//还尝试了multipartcontent,但没有成功
//var multipartContent=新的MultipartFormDataContent();
//multipartContent.Add(续,“图像”);
如果(isNewItem)
{
var response=await client.PostAsync(uri,cont).ConfigureAwait(false);
if(响应。IsSuccessStatusCode)
{
var res=await response.Content.ReadAsStringAsync().ConfigureAwait(false);
返回res;
Debug.WriteLine(@“用户已成功保存”);
}
}
}
捕获(例外情况除外)
{
}
}
使用cont.Headers.ContentType=MediaTypeHeaderValue.Parse(“应用程序/json”)

我收到另一个错误消息:

反序列化操作的请求消息正文时出错 “上传用户”。OperationFormatter遇到无效的消息正文。 应找到名为“type”且值为“object”的属性。 找到值“string”

Wireshark展示了这一点:

已更改发送到此的方法:

 var senderPackage = new Dictionary<string, byte[]>
                {
                    {"image", messageBytes}
                };               
                var json = JsonConvert.SerializeObject(senderPackage);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
var senderPackage=新字典
{
{“图像”,messageBytes}
};               
var json=JsonConvert.SerializeObject(senderPackage);
var content=newstringcontent(json,Encoding.UTF8,“application/json”);
出现新错误:

格式化程序在尝试反序列化 消息:尝试反序列化参数时出错 . InnerException消息为“There was” 反序列化System.Byte[]类型的对象时出错。末端元件 应为命名空间“”中的“图像”。找到的文本 “II85AI80QUFRU2TASLJNQUJBUUFBQVFBQKFBR8YD0JEQUJZU0ZCYVFUNYRMHZUHCC2DLRULYS0NVBETGRTZQVEJDWUZWBFPGOVZYVNRXZUPTQMFUR1JMXRKAGJKJWJYWDOHLICW14NW1VCTZULZJ3QKRBUNLNAKTFNHJLZRMDZRYMWXBLU2TWS1NRCETTAI2TWS12TTAI2TWS.”

Wireshark数据包如下所示:

如果有人想出办法让它发挥作用,我将永远欠你的债;)

您应该在json的请求头中使用“application/json”作为媒体类型

尝试:

  • cont.Headers.ContentType=MediaTypeHeaderValue.Parse(“应用程序/json”)
  • RequestFormat=WebMessageFormat.Json
    到您的
    界面
  • 正文应包含一个键“image”,其值为字节列表

     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
    

最后,我创建了自己的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";
        }

是的,我不知道怎么做,但我尝试将其添加为var multipartContent=new MultipartFormDataContent();multipartContent.Add(续,“图像”);但这并没有起作用。。我应该如何将数组链接到“image”?也尝试了更改BodyStyle=WebMessageBodyStyle.Bare,但这不起作用。您可以用新的wireshark包图像发布json stringupdated问题您的值似乎是一个字符串,它必须是一个字节数组工作解决方案:var json=“{\”image\:[“+string.Join(,”,item.缩略图) + "] }"; var content=新的StringContent(json);content.Headers.ContentType=MediaTypeHeaderValue.Parse(“应用程序/json”);var response=await client.PostAsync(uri,内容).ConfigureAwait(false);
 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);