2017-02-23 105 views
0

我对使用RestSharp的发布请求有问题。我有2类:RestSharp - 发布发布请求(操作失败)

public class UnitToPost 
     { 
      public bool floating_point { get; set; } 
      public Dictionary<string, TranslationUnitToPost> translations { get; set; } 
     } 

     public class TranslationUnitToPost 
     { 
      public string name { get; set; } 
     } 

而且我想与POST请求发送:

 client = new RestClient(adresApi); 

     client.AddDefaultHeader("Authorization", "Bearer " + key);   

     IRestRequest updateProduct = new RestRequest("units", Method.POST); 

     ShoperModel.UnitToPost unitToPost = new ShoperModel.UnitToPost(); 
     unitToPost.floating_point = true; 
     ShoperModel.TranslationUnitToPost transUnit = new ShoperModel.TranslationUnitToPost(); 
     transUnit.name = "namename"; 
     unitToPost.translations = new Dictionary<string, ShoperModel.TranslationUnitToPost>(); 
     unitToPost.translations.Add("pl_PL", transUnit); 


     updateProduct.RequestFormat = RestSharp.DataFormat.Json; 
     updateProduct.AddBody(unitToPost); 

     IRestResponse updateProductResponse = this.client.Execute(updateProduct); 

,我总是得到一个错误:

[RestSharp.RestResponse] = "StatusCode: InternalServerError, Content-Type: application/json, Content-Length: -1)"

Content = "{\"error\":\"server_error\",\"error_description\":\"Operation Failed\"}"

什么是它的原因是什么?难道是因为我班上的字典?

回答

0

我运行了你的代码,它发出一个有效的JSON体的请求。

POST http://..../units HTTP/1.1

Accept: application/json,application/xml, text/json, text/x-json, text/javascript, text/xml Authorization: Bearer a

User-Agent: RestSharp/105.2.3.0

Content-Type: application/json

Host: .....

Content-Length: 84

Accept-Encoding: gzip, deflate

Connection: Keep-Alive

{"floating_point":true,"translations":[{"Key":"pl_PL","Value":{"name":"namename"}}]}

看起来问题可能与接收服务器有关。如果你还没有这样做,我会建议运行Fiddler(http://www.telerik.com/fiddler)并检查请求/响应。

编辑...

我才刚刚意识到你想要的JSON体是: - { “floating_point”:真正的 “翻译”:{ “pl_PL”:{ “名”: “namename” }}}

我没有找到覆盖这个RestSharp问题: - https://github.com/restsharp/RestSharp/issues/696

这包括有人使用ExpandoObject获得所需要的结果后。

http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/

不过,我发现它更容易使用JSON .NET序列化并用下面的代码定身: -

updateProduct.AddBody(JsonConvert.SerializeObject(unitToPost));