Serialization Management in Web API / APIController

Where can I specify custom serialization / deserialization in ASP.NET web API?

The performance of our application requires fast serialization / deserialization of messages, so we need to tightly control this part of the code in order to either use our home-brew or OSS.

I checked various sources such as this , which explains how to create a custom value provider, but I have yet to see an example that explains the process ends.

Can someone send / show me a way to serialize incoming / outgoing messages?

Also evaluated is a diagram of various insertion points / events in the web API, similar to this one for WCF !

+7
source share
2 answers

The extension point you are looking for is MediaTypeFormatter. It controls reading from the request body and writing to the response body. This may be the best resource for writing your own formatting:

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

+6
source

Here's an example code in case the 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.

+1
source

All Articles