26 September 2016

C# - Serialize Object to XML HttpResponseMessage

Sometimes we have an explicit requirement to serialize a C# object to XML HttpResponseMessage format.

This generic function can be used to achieve this conversion -

public static HttpResponseMessage CreateXmlResponse<T>(T objectToSerialize)
{
    return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ObjectContent<T>(objectToSerialize,
                                        new System.Net.Http.Formatting.XmlMediaTypeFormatter
                                        {
                                            UseXmlSerializer = true
                                        })
    };
}


The function takes an object of type 'T' as input and serializes it using XMLMediaTypeFormatter XML serializer available in .NET namespace System.Net.Http.Formatting.

A sample function call be like this - 

var response = CreateXmlResponse<ObjectClass>(object);

No comments: