boilers222
boilers222

Reputation: 1989

How do I get my API request to use XML instead of parameters?

I've created an API in C# that takes 4 parameters. This is working fine. What would I have to do to get it to accept an XML file instead of parameters?

Here's the code:

public string Post(int orderID, bool internalUse, string subject, string message)
{
    return "orderID: " + orderID + "; internalUse: " + internalUse + "; subject: " + subject + "; message: " + message;
}

I can call it from Postman using a Post request like this:

http://localhost:58069/api/values/SendEmail?orderID=1234&internalUse=true&subject=Hello&message=Hello World

I'd rather use an XML document where the URL would look like this:

http://localhost:58069/api/values/SendEmail

and the parameters would be specified in an XML file.

I tried using this XML file (also tried it with & without the parameters nested in the response tag and with & without the XML version tag):

<?xml version="1.0" encoding="utf-8" ?>
<response>
    <orderID>1234</orderID>
    <internalUse>true</internalUse>
    <subject>Hello</subject>
    <message>Hello World</message>
</response>

Here's how the request looks in Postman:

enter image description here

This hits my SendEmail method, but all the variables are blank. Is there something I need to do on the code side or am I just not creating the Postman request correctly?

Upvotes: 0

Views: 850

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14251

Create model to reflect your xml:

[XmlRoot("response")]
public class Response
{
    [XmlElement("orderID")]
    public int OrderID { get; set; }
    [XmlElement("internalUse")]
    public bool InternalUse { get; set; }
    [XmlElement("subject")]
    public string Subject { get; set; }
    [XmlElement("message")]
    public string Message { get; set; }
}

Change method signature. Use FromBody attribute.

public string Post([FromBody] Response response)
{
    return "orderID: " + response.OrderID +
        "; internalUse: " + response.InternalUse +
        "; subject: " + response.Subject +
        "; message: " + response.Message;
}

Add support for XmlSerializer:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddXmlSerializerFormatters();
}

I assume that you are using ASP.NET Core.

Upvotes: 5

Related Questions