hckr.fyi // thoughts

Where to set the Custom Serializer in ASP.NET Web API

by Michael Szul on

There are a few areas in .NET development where searching for online documentation or code examples can be tricky because newer versions have a different way of doing things, but online searches reveal solutions for much older problems that might not work. This is especially true for technologies like Entity and Web API.

For this Quick Bytes post, I'll give an example of where to set the custom serializer for Web API output. In a future blog post, I'll show you how to create a custom serializer to modify XML output in the Web API.

The best place to put your custom serializer code is in the App_Start/WebApiConfig.cs file:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.EnableSystemDiagnosticsTracing();
        }
    }
    

This the default file with the standard routing. In this file, add your serialization changes:

var xml = config.Formatters.XmlFormatter;
    xml.UseXmlSerializer = true;
    xml.SetSerializer<YOUR_MODEL>(new XmlSerializer(typeof(YOUR_MODEL)));
    

In this example code, I'm grabbing the XML formatter, setting the serialization switch, and then replacing the default serializer with the custom serializer. Notice that SetSerializer<> is the generics version that accepts an Entity model. This allows you to replace only the serializer for the specific model you want to modify, which comes in handy if you have different requirements per model.

I normally place this code at the top of the class:

public static void Register(HttpConfiguration config)
    {
        var xml = config.Formatters.XmlFormatter;
        xml.UseXmlSerializer = true;
        xml.SetSerializer<YOUR_MODEL>(new XmlSerializer(typeof(YOUR_MODEL)));
    
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    
       config.EnableSystemDiagnosticsTracing();
    }