RestSharp发送字典
本文关键字:字典 RestSharp | 更新日期: 2023-09-27 18:03:44
我已经看到了如何从响应中反序列化字典,但是如何发送字典呢?
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);
呃…是别的东西搞砸了我的案子。正如@Chase所说,这很简单:
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
试着这样做,这是我的一个简单的帖子的例子,我更喜欢用这种风格的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
参数