TCM
TCM

Reputation: 16900

Returning XML from web api changes field name

I have this class which I am trying to return as XML from my web api method:

[Serializable]
public partial class LoggedInUser
{
    public int UserID { get; set; }

    public string EmailAddress { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public short RoleID { get; set; }

    public short UserStatusID { get; set; }

    public DateTime LastLoginDateTime { get; set; }

}

Web API method is simple:

[HttpGet]
public LoggedInUser Me()
{
    var user = new LoggedInUser() { FirstName = "Test"  };
    return user;
}

This is what I get in XML when I hit the method from browser:

<_x003C_FirstName_x003E_k__BackingField>Test</_x003C_FirstName_x003E_k__BackingField>

Notice how FirstName changes to some other field name. This is due to the presence of [Serializable] attribute which I need is as this is the same class which is used to store info in session when Session state is outProc

How can I fix this such that even though the Serializable attribute is present it would return the field name in response same as class definition.

Upvotes: 1

Views: 671

Answers (2)

JotaBe
JotaBe

Reputation: 39045

By default the XmlMediaTypeFormmatter of Web API uses the DataContractSerializer.

When this serializer serializes auto-properties, it adds the infamous xxx_BackingField to the serialized properties. To avoid this you can do two different things:

  • decorate all the autoproperties with [DataMember], and keep using the default DataContractSerializer
  • Change the xml media type formatter default serializer to use XmlSerializer instead. You can change the configuration in global.asax like this: GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; See MSDN reference for XmlMediaTypeFormatter.UseXmlSerializer Property for more information.

Using an anonymous type, like suggested in the other answer, avoids the problem because the anonymous class doesn't have a [DataContract] attribute. The problem is that, with that option, you always have to use anonymous types, and that can require a lot of typing, and even be error prone.

Upvotes: 3

Schadensbegrenzer
Schadensbegrenzer

Reputation: 950

When Serializable Attribute is required I always return an anonymous type.

public dynamic Me()
{
    var user = new LoggedInUser() { FirstName = "Test" };
    return new {FirstName = user.FirstName};
}

Upvotes: 1

Related Questions