RestSharp 发送字典
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);
尝试这样做,这是我的简单示例 post 为您准备了一些东西,我更喜欢以这种方式使用 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
参数。
呃...我的案子搞砸了。作为,很简单:
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
的回显服务
我已经了解了如何从响应中反序列化字典,但是您如何发送字典?
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);
尝试这样做,这是我的简单示例 post 为您准备了一些东西,我更喜欢以这种方式使用 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
参数。
呃...我的案子搞砸了。作为
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
的回显服务