Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerializer ignores [XmlAttribute] in WebApi

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?

like image 840
GTHvidsten Avatar asked Mar 13 '23 00:03

GTHvidsten


1 Answers

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.

like image 91
James Dev Avatar answered Mar 24 '23 09:03

James Dev