4

I have a WebApi that returns a simple object, but when I'm forcing it to return as XML (Accept: application/xml) it ignores the [XmlAttribute] attribute I've set on the object.

This is my object:

public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
}

And I return it like this in the code:

[RoutePrefix("api/mytest")]
public class MyTestController : System.Web.Http.ApiController
{
    [HttpGet]
    [Route("gettest")]
    public Foo GetTest()
    {
        return new Foo() { Bar = "foobar" };
    }
}

The resulting XML is:

<Foo>
    <Bar>foobar</Bar>
</Foo>

Whereas I would expect it to be returned like this:

<Foo Bar="foobar">
</Foo>

Why does the XmlSerializer used by WebApi ignore the [XmlAttribute] attribute, and how can I make it work like I want to?

TheHvidsten
  • 4,028
  • 3
  • 29
  • 62
  • What is the type of the "simple object"? I have a feeling your Foo Bar isn't your real code. – Frozenthia Mar 07 '16 at 15:01
  • You are right that Foo Bar isn't my real code, but I actually did recreate the issue with what I described in my question, so my real code doesn't matter as Foo Bar also fails. – TheHvidsten Mar 07 '16 at 15:07

2 Answers2

6

Try setting this global configuration value in your WebApi to true

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

By default Web API uses DataContractSerializer in XmlMediaTypeFormatter.

James Dev
  • 2,979
  • 1
  • 11
  • 16
  • I have a `HttpConfiguration` configuration object, and I did a `config.Formatters.XmlFormatter.UseXmlSerializer = true;` on the object being used to start the WebApi. Unfortunately that had no effect. – TheHvidsten Mar 07 '16 at 15:10
1

This worked for me... no need to change global configuration.

var configuration = new HttpConfiguration();
configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
return Request.CreateResponse(HttpStatusCode.OK, myObjectToSerialize, configuration);
Tomino
  • 5,969
  • 6
  • 38
  • 50