2015-07-20 49 views
0

我已经看过如何从响应中反序列化字典,但是如何发送字典呢?RestSharp send Dictionary

var d = new Dictionary<string, object> { 
    { "foo", "bar" }, 
    { "bar", 12345 }, 
    { "jello", new { qux = "fuum", lorem = "ipsum" } } 
}; 

var r = new RestRequest(url, method); 
r.AddBody(d); // <-- how? 

var response = new RestClient(baseurl).Execute(r); 

回答

1

呃...这是别的东西搞砸了我的情况。由于@Chase said,这很简单:

var c = new RestClient(baseurl); 
var r = new RestRequest(url, Method.POST); // <-- must specify a Method that has a body 

// shorthand 
r.AddJsonBody(dictionary); 

// longhand 
r.RequestFormat = DataFormat.Json; 
r.AddBody(d); 

var response = c.Execute(r); // <-- confirmed* 

不需要包装字典作为另一个对象。

(*)证实,它发送预期JSON的带有回声服务诸如Fiddler,或RestSharp的SimpleServer

1

尝试做这样的事情,这是我简单的职位有一些东西,你的例子,我更喜欢使用RestSharp这种风格,因为它是更清洁,然后用它的其他变体:

var myDict = new Dictionary<string, object> { 
    { "foo", "bar" }, 
    { "bar", 12345 }, 
    { "jello", new { qux = "fuum", lorem = "ipsum" } } 
}; 
var client = new RestClient("domain name, for example http://localhost:12345"); 
var request = new RestRequest("part of url, for example /Home/Index", Method.POST); 
request.RequestFormat = DataFormat.Json; 
request.AddBody(new { dict = myDict }); // <-- your possible answer 
client.Execute(request); 

对于本示例,端点在声明中应该有dict参数。