RestSharp send Dictionary

為{幸葍}努か 提交于 2019-12-13 05:57:03

问题


I've seen how to deserialize a dictionary from the response, but how do you send one?

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:


Ugh...it was something else screwing up my case. As @Chase said, it's pretty simple:

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*

Didn't need to wrap the dictionary as another object.

(*) confirmed that it sent expected JSON with an echo service like Fiddler, or RestSharp's SimpleServer




回答2:


Try to do it something like this, it's my example of simple post with some stuff for you, I prefer use RestSharp in this style because it's much cleaner then other variants of using it:

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

And for this example endpoint should have dict parameter in declaration.



来源:https://stackoverflow.com/questions/31526400/restsharp-send-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!