2017-02-23 106 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));