Building XML request with RestSharp

≯℡__Kan透↙ 提交于 2019-12-04 06:53:19

By default RestSharp is using its own serializer but it also packs the DotNetSerializer so you achieve your goal by changing the serializer like this:

var request = new RestRequest("theresource", Method.POST) 
{ 
    RequestFormat = DataFormat.Xml, 
    XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer() 
};

Then you can use a list of message objects and decorate it with XmlElement attribute:

public class messages
{
    public string accountreference { get; set; }

    public string from { get; set; }

    [XmlElement("message")]
    public List<message> messageList { get; set; }
}


public class message
{
    public string to { get; set; }

    public string body { get; set; }
}

Then you can change the last bit to add multiple messages:

request.AddBody(
    new messages
    {
        accountreference = "ref",
        from = "from",
        messageList = new List<message>() {
                new message { to = "to1", body = "body1" },
                new message { to = "to2", body = "body2" }
                }
    }); 

which would produce (I got the XML by checking request.Parameters[0].Value):

<?xml version="1.0" encoding="utf-8"?>
<messages>
  <accountreference>ref</accountreference>
  <from>from</from>
  <message>
    <to>to1</to>
    <body>body1</body>
  </message>
  <message>
    <to>to2</to>
    <body>body2</body>
  </message>
</messages>

I guess this is the XML format you've been looking for.

Arvin

Having message as list will work -

public class messages
{
    public string accountreference { get; set; }

    public string from { get; set; }

    public List<message> message { get; set; }
}

public class message
{
    public string to { get; set; }

    public string body { get; set; }
}

Check the very last answer here -

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

If you face issues with list, try this -

Can RestSharp send a List<string> in a POST request?

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