huddds huddds - 2 years ago 140 Question

Web API Receive XML from another API in VB.NET

I'm new to web api's but do have a strong knowledge of VB.NET for website development. I'm trying to build an api that will receive xml from another api. I have my domain set up with the initial web api framework. I just need to know what function to use to accept and use the xml the other api is posting to my new api. The xml being passed is shown below. I'm trying to store these into variables which I will post to my table upon receiving them.

Any help with this would be great as I've spent days researching but can't quite search the right terms to find what I'm looking for. Thanks in advance for any responses.

Example xml being posted from external API


Answer Source

You have at least 2 options of how to do it.

But first you will need to create a class model that will represent your XML. It may look like that:

[XmlRoot("exAPI", Namespace = "")]
public class ExApi
    public Client Client { get; set; }

public class Client
    public int Id { get; set; }

    public string Key { get; set; }

    public string Ref { get; set; }

Automatic parameter binding. For this method to work you need to check if Content-Type: application/xml HTTP header is present in request from external API. This can be also Content-Type: text/xml. If it is, the you will need to change XmlFormatter. By default Web API uses DataContractSerializer but it will be very difficult to deserialize your XML. Just add this code to your Global.asax Application_Start method:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

And you controller method might look like that:

public void Post(ExApi exApi)
    // XML is automatically deserialized in exApi parameter

You can read more about parameter binding in this article and about custom XML serialization in this one.

Getting raw XML data from request. If Content-Type header is missing then you will need to read contents of the request manually and then parse XML:

public void Post(HttpRequestMessage req)
    using (var xml = req.Content.ReadAsStreamAsync().Result)
        var deserializer = new XmlSerializer(typeof (ExApi));
        using (var xmlReader = XmlReader.Create(xml))
            var obj = (ExApi)deserializer.Deserialize(xmlReader);

Note that method parameter is of type HttpRequestMessage which allows you to read contents of the request.

NOTE: Sorry it's not a VB.NET but I think you will manage to convert it from C#.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download