1

I want to use DataContractSerializer to serialize the responses and XmlSerializer to deserialize the xml in incoming requests. Is it possible? I know I can use different serializers for different types but I want different serializers for read and write.

1 Answer 1

3

That seems like a really odd request, but yes it's possible. You can create a custom MediaType formatter like this:

public class DcsXsFormatter : MediaTypeFormatter
{
    public DataContractXmlFormatter()
    {
        SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml"));
        SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml"));
    }

    public override bool CanWriteType(Type type)
    {
        return true;
    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, 
                                                     HttpContent content, 
                                                     IFormatterLogger formatterLogger)
    {
        var task = Task<object>.Factory.StartNew(() =>
            {
                var ser = new XmlSerializer(type);
                return ser.Deserialize(readStream);
            });

        return task;
    }

    public override Task WriteToStreamAsync(Type type, object value, 
                                    Stream writeStream, 
                                    HttpContent content, 
                                    TransportContext transportContext)
    {            
        var task = Task.Factory.StartNew( () =>
            {                    
                var ser = new DataContractSerializer(type);
                ser.WriteObject(writeStream,value);                    
                writeStream.Flush();
            });

        return task;
    }
}

To hook it up in global.asax:

// remove existing XmlFormatter config.Formatters.Remove(config.Formatters.XmlFormatter);

// Hook in your custom XmlFormatter
config.Formatters.Insert(0, new  DcsXsFormatter());

But why would you want to do this?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.