RestSharp发送字典

时间:2015-07-20 21:09:13

标签: c# restsharp

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

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);

2 个答案:

答案 0 :(得分:2)

呃......这是别的事情搞砸了我的情况。作为@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*

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

(*)确认它使用像Fiddler或RestSharp的SimpleServer

之类的回应服务发送了预期的JSON

答案 1 :(得分: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参数。