Controlling serialization in Web API / APIController Controlling serialization in Web API / APIController asp.net asp.net

Controlling serialization in Web API / APIController


The extension point you're looking for is the MediaTypeFormatter. It controls reading from the request body and writing to the response body. This might be the best resource for writing your own formatter:

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters


Here's code example in case link in the answer above dies

public class MerlinStringMediaTypeFormatter : MediaTypeFormatter{    public MerlinStringMediaTypeFormatter()    {        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));    }    public override bool CanReadType(Type type)    {        return type == typeof (YourObject); //can it deserialize    }    public override bool CanWriteType(Type type)    {        return type == typeof (YourObject); //can it serialize    }    public override Task<object> ReadFromStreamAsync(         Type type,         Stream readStream,         HttpContent content,         IFormatterLogger formatterLogger)    {        //Here you put deserialization mechanism        return Task<object>.Factory.StartNew(() => content.ReadAsStringAsync().Result);    }    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)    {        //Here you would put serialization mechanism        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);    }}

Then you need to register your formatter in Global.asax

protected void Application_Start()    {        config.Formatters.Add(new MerlinStringMediaTypeFormatter());    }

Hope this saves you some time.