Understanding Custom WCF Web API Media Type Formatters on Both Server and Client

Media Type Formatters in the WCF Web API provide a way for the consumer of your service to not only specify the format they want for their response, but also specify the format they are using on their request. Typically the desired response format is specified in the "Accept" request header and the request body format is specified in the "Content-Type" request header. Media types are central to building any RESTful service. Two of the most common media types are "application/xml" and "application/json". However, to build a truly RESTful service that is hypermedia driven, these media types should not be used. Instead, a media type that indicates the specifics of your application domain and has rich semantics for hypermedia is preferred.

REST is an architectural style that is governed by a guiding set of principles. While adhering to these principles, there is no one right way to do things. Recently, Darrel Miller turned me on the HAL (Hypermedia Application Language) which was created by Mike Kelly. I really like the well-structured style that HAL has – making it easy and flexible to embed hypermedia in your resources. Although HAL is an XML-based media type, it is not just "application/xml" because of the specific rules that govern its format. We could accomplish this format with some well placed attributes that control XML serialization but instead let's create our own custom Media Type Formatter to create the format. Media Type Formatters expose OnWritetoStream() and OnReadFromStream() methods to allow serialization/deserialization. Quite often people think of media type formatters as only being used on the server. However, they can be used on the client side as well to control serialization/deserialization of the requests. The following diagram shows the process of an HTTP request/response and the role that the Media Type Formatter plays:

For my example, I'm going to use the Nerd Dinner domain since it's something most people are familiar with. I could just use "application/hal" for my media type but instead I'm going to use "application/vnd.nerddinner.hal+xml" to more clearly indicate the specifics of my application's domain ("vnd" indicates a vendor specific domain). One of the core tenets of REST services is loose coupling between the client and server which allows evolvability. Clients need to know about the bookmark URI (i.e., the "home page" so to speak) but should not have knowledge of any other URIs. Instead clients must understand the link relations (i.e., "rel" attributes of the elements) and just "follow the links."

If I request my well-known "bookmark URI", to get a specific dinner, it would look like this:

Notice I passed an Accept header of "application/vnd.nerddinner.hal+xml". Also notice the three elements that came back in my response – this is my hypermedia. The Link Relations are in URI format and the client must have knowledge of what these mean.

My Dinner class just looks like this:

public class Dinner : HalResource
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Address { get; set; }
    public string ContactPhone { get; set; }
    public string Country { get; set; }
    public DateTime EventDate { get; set; }
    public string HostedBy { get; set; }
}

The HalResource base class just defines the standard HAL attributes:

public abstract class HalResource
{
    public HalResource()
    {
        this.Links = new List<Link>();
    }
 
    public string Rel { get; set; }
    public string HRef { get; set; }
    public string LinkName { get; set; }
    public List<Link> Links { get; set; }
}

The code snippet below shows what my custom HalMediaTypeFormatter currently looks like. Notice line #18 in the constructor shows the media types that the formatter is intended to support.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using Microsoft.ApplicationServer.Http;
 
namespace NerdDinnerWebApi.ResourceModel
{
    public class HalMediaTypeFormatter : MediaTypeFormatter
    {
        public HalMediaTypeFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.nerddinner.hal+xml"));
        }
 
        public override object OnReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders)
        {
            var instance = Activator.CreateInstance(type);
            var xml = XElement.Load(stream);
 
            // First set the well-known HAL elements
            type.GetProperty("Rel").SetValue(instance, xml.Attribute("rel").Value, null);
            type.SetPropertyValueFromString("HRef", xml.Attribute("href").Value, instance);
 
            var links = xml.Elements("link");
            Console.WriteLine("links count: " + links.Count());
            var linksList = new List<Link>();
            foreach (var link in links)
            {
                linksList.Add(new Link { Rel = link.Attribute("rel").Value, HRef = link.Attribute("href").Value });
            }
            type.GetProperty("Links").SetValue(instance, linksList, null);
 
            // Now set the rest of the properties
            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty))
            {
                Console.WriteLine("setting property: " + property.Name);
                type.SetPropertyValue(property.Name, xml.Element(property.Name), instance);
            }
 
            return instance;
        }
 
        public override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
 
            var writer = XmlWriter.Create(stream, settings);
            var resource = value as HalResource;
            if (resource != null)
            {
                writer.WriteStartElement("resource");
                writer.WriteAttributeString("rel", "self");
                writer.WriteAttributeString("href", resource.HRef);
 
                foreach (var link in resource.Links)
                {
                    writer.WriteStartElement("link");
                    writer.WriteAttributeString("rel", link.Rel);
                    writer.WriteAttributeString("href", link.HRef);
                    writer.WriteEndElement();
                }
 
                foreach (var property in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
                {
                    if (ShouldWriteProperty(property))
                    {
                        var propertyString = GetPropertyString(property, value);
                        if (propertyString != null)
                        {
                            writer.WriteElementString(property.Name, propertyString);
                        }
                    }
                }
 
                writer.WriteEndElement();
                writer.Flush();
            }
        }
 
        private static bool ShouldWriteProperty(PropertyInfo property)
        {
            var nonSerializedProperties = new[] { "Rel", "HRef", "LinkName" };
            var typesToSerialize = new[] { typeof(int), typeof(string), typeof(DateTime) };
 
            if (nonSerializedProperties.Contains(property.Name))
            {
                return false;
            }
 
            return typesToSerialize.Contains(property.PropertyType);
        }
 
        private static string GetPropertyString(PropertyInfo property, object instance)
        {
            var propertyValue = property.GetValue(instance, null);
            if (property.PropertyType.IsValueType || propertyValue != null)
            {
                return propertyValue.ToString();
            }
            return null;
        }
    }
}

The code is not yet Production ready because it only handles a few primitives types and it is still incomplete with respect to the way HAL handles child collections but it gives a good flavor of both serialization/deserialization directions for a custom media type formatter. To tell the Web API to use this formatter, you can just add this configuration to your start up code (e.g., Global.asax or a PreApplicationStartMethod). The key is on line #20 below:

using System;
using System.Web.Routing;
using Microsoft.ApplicationServer.Http.Activation;
using Microsoft.ApplicationServer.Http.Description;
using NerdDinnerWebApi.ResourceModel;
using NerdDinnerWebApi.Services.Infrastructure;
using NerdDinnerWebApi.Services.Services;
 
[assembly: WebActivator.PreApplicationStartMethod(typeof(NerdDinnerWebApi.Services.App_Start.ServicesInitializer), "Start")]
 
namespace NerdDinnerWebApi.Services.App_Start
{
    public static class ServicesInitializer
    {
        public static void Start()
        {
            var iocContainer = StructureMapBootstrapper.Initialize();
            var config = HttpHostConfiguration.Create()
                .SetResourceFactory(new StructureMapResourceFactory(iocContainer))
                .AddFormatters(new HalMediaTypeFormatter());
            RouteTable.Routes.MapServiceRoute<DinnerService>("dinners", config);
        }
    }
}

Finally, let's see what the code looks like on this client side:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.ApplicationServer.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NerdDinnerWebApi.ResourceModel;
using FluentAssertions;
 
namespace WebApiTests
{
    [TestClass]
    public class DinnerServiceTests
    {
        private const string baseUri = "http://localhost:1700";
        private static readonly MediaTypeWithQualityHeaderValue halMediaTypeHeader = new MediaTypeWithQualityHeaderValue("application/vnd.nerddinner.hal+xml");
        private static readonly MediaTypeFormatter[] formatters = new[] { new HalMediaTypeFormatter() };
 
        [TestMethod]
        public void Hal_formatter_should_serialize_request_for_dinner_resource()
        {
            // arrange
            var httpClient = new HttpClient(baseUri);
            httpClient.DefaultRequestHeaders.Accept.Add(halMediaTypeHeader);
 
            // act
            var response = httpClient.Get("/dinners/1");
            var dinnerResource = response.Content.ReadAs<Dinner>(formatters);
 
            // assert
            dinnerResource.Should().NotBeNull();
            dinnerResource.Rel.Should().Be("self");
            dinnerResource.HRef.Should().EndWith("/dinners/1");
            dinnerResource.DinnerId.Should().Be(1);
            dinnerResource.Title.Should().Be("MVC Dinner");
            dinnerResource.Description.Should().Be("This dinner will be for MVC developers.");
            dinnerResource.Address.Should().Be("123 Main Street");
            dinnerResource.EventDate.Should().Be(new DateTime(2011, 7, 1));
            dinnerResource.Country.Should().Be("USA");
            dinnerResource.Links.Count.Should().Be(3);
        }
    }
}

There are a couple of very important things to note in the code above. First, on line #23 I am setting the Accept header of the request (the variable was defined on line #15). Second, when I deserialize the xml to a .NET object on line #27, I pass the formatters in (which is just my HalMediaTypeFormatter) so that it knows how to deal with this request. If I don't do this correctly, I'll get an InvalidOperationException: No 'MediaTypeFormatter' is available to read an object of type with the media type .

As you can see from the example above, I'm using the same custom Media Type Formatter on both the server and the client.

As I mentioned earlier in this post, the coupling between the client and server should be focused on defining the link relations for your media types. Stay tuned for my next post where I'll show a mechanism for leveraging a media type formatter (like the one shown in this post) to generate documentation for consumers of your service so that consumers can fully understand all hypermedia link relations.

The complete solution for the code sample above can be downloaded here.