Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove namespace from WEB API Response

Please help me to remove xmlns namespace from the WEB API Response.

Adding,

config.Formatters.XmlFormatter.UseXmlSerializer = true;

(or)

[DataContract(Namespace="")]

didn't help me. Your help is much appreciated.

like image 334
Pitchai P Avatar asked Dec 13 '12 13:12

Pitchai P


1 Answers

Finally, I found the solution. Just created a CustomXmlFormatter to remove the namespace from the root element.

public class IgnoreNamespacesXmlMediaTypeFormatter : XmlMediaTypeFormatter
{
 public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
    try
    {
        var task = Task.Factory.StartNew(() =>
        {
            var xns = new XmlSerializerNamespaces();
            var serializer = new XmlSerializer(type);
            xns.Add(string.Empty, string.Empty);
            serializer.Serialize(writeStream, value, xns);
        });

        return task;
    }
    catch (Exception)
    {
        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
    }
   }
}
like image 82
Pitchai P Avatar answered Nov 15 '22 09:11

Pitchai P