【问题标题】:RestSharp send DictionaryRestSharp 发送字典
【发布时间】:2022-02-01 22:41:23
【问题描述】:

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

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

【问题讨论】:

    标签: c# dictionary deserialization restsharp


    【解决方案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*
    

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

    (*) 确认它使用 Fiddler 或 RestSharp 的 SimpleServer 等回显服务发送了预期的 JSON

    【讨论】:

      【解决方案2】:

      尝试这样做,这是我的简单帖子示例,其中包含一些内容,我更喜欢在这种风格中使用 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 参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-13
        • 2014-03-19
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2013-08-22
        • 2015-03-03
        相关资源
        最近更新 更多