Steve Michelotti

A .NET Developer's Toolbox

  Home  |   Contact  |   Syndication    |   Login
  201 Posts | 0 Stories | 1110 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Code

Publications

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:

 

mediatypeformatterprocess

 

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 <link> elements) and just “follow the links.”

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

 

nerddinnerxml

 

Notice I passed an Accept header of “application/vnd.nerddinner.hal+xml”. Also notice the three <link> 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:

   1:  public class Dinner : HalResource
   2:  {
   3:      public int DinnerId { get; set; }
   4:      public string Title { get; set; }
   5:      public string Description { get; set; }
   6:      public string Address { get; set; }
   7:      public string ContactPhone { get; set; }
   8:      public string Country { get; set; }
   9:      public DateTime EventDate { get; set; }
  10:      public string HostedBy { get; set; }
  11:  }

The HalResource base class just defines the standard HAL attributes:

   1:  public abstract class HalResource
   2:  {
   3:      public HalResource()
   4:      {
   5:          this.Links = new List<Link>();
   6:      }
   7:   
   8:      public string Rel { get; set; }
   9:      public string HRef { get; set; }
  10:      public string LinkName { get; set; }
  11:      public List<Link> Links { get; set; }
  12:  }

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.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.IO;
   4:  using System.Linq;
   5:  using System.Net;
   6:  using System.Net.Http.Headers;
   7:  using System.Reflection;
   8:  using System.Xml;
   9:  using System.Xml.Linq;
  10:  using Microsoft.ApplicationServer.Http;
  11:   
  12:  namespace NerdDinnerWebApi.ResourceModel
  13:  {
  14:      public class HalMediaTypeFormatter : MediaTypeFormatter
  15:      {
  16:          public HalMediaTypeFormatter()
  17:          {
  18:              this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.nerddinner.hal+xml"));
  19:          }
  20:   
  21:          public override object OnReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders)
  22:          {
  23:              var instance = Activator.CreateInstance(type);
  24:              var xml = XElement.Load(stream);
  25:   
  26:              // First set the well-known HAL elements
  27:              type.GetProperty("Rel").SetValue(instance, xml.Attribute("rel").Value, null);
  28:              type.SetPropertyValueFromString("HRef", xml.Attribute("href").Value, instance);
  29:   
  30:              var links = xml.Elements("link");
  31:              Console.WriteLine("links count: " + links.Count());
  32:              var linksList = new List<Link>();
  33:              foreach (var link in links)
  34:              {
  35:                  linksList.Add(new Link { Rel = link.Attribute("rel").Value, HRef = link.Attribute("href").Value });
  36:              }
  37:              type.GetProperty("Links").SetValue(instance, linksList, null);
  38:   
  39:              // Now set the rest of the properties
  40:              foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty))
  41:              {
  42:                  Console.WriteLine("setting property: " + property.Name);
  43:                  type.SetPropertyValue(property.Name, xml.Element(property.Name), instance);
  44:              }
  45:   
  46:              return instance;
  47:          }
  48:   
  49:          public override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
  50:          {
  51:              XmlWriterSettings settings = new XmlWriterSettings();
  52:              settings.Indent = true;
  53:   
  54:              var writer = XmlWriter.Create(stream, settings);
  55:              var resource = value as HalResource;
  56:              if (resource != null)
  57:              {
  58:                  writer.WriteStartElement("resource");
  59:                  writer.WriteAttributeString("rel", "self");
  60:                  writer.WriteAttributeString("href", resource.HRef);
  61:   
  62:                  foreach (var link in resource.Links)
  63:                  {
  64:                      writer.WriteStartElement("link");
  65:                      writer.WriteAttributeString("rel", link.Rel);
  66:                      writer.WriteAttributeString("href", link.HRef);
  67:                      writer.WriteEndElement();
  68:                  }
  69:   
  70:                  foreach (var property in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
  71:                  {
  72:                      if (ShouldWriteProperty(property))
  73:                      {
  74:                          var propertyString = GetPropertyString(property, value);
  75:                          if (propertyString != null)
  76:                          {
  77:                              writer.WriteElementString(property.Name, propertyString);
  78:                          }
  79:                      }
  80:                  }
  81:   
  82:                  writer.WriteEndElement();
  83:                  writer.Flush();
  84:              }
  85:          }
  86:   
  87:          private static bool ShouldWriteProperty(PropertyInfo property)
  88:          {
  89:              var nonSerializedProperties = new[] { "Rel", "HRef", "LinkName" };
  90:              var typesToSerialize = new[] { typeof(int), typeof(string), typeof(DateTime) };
  91:   
  92:              if (nonSerializedProperties.Contains(property.Name))
  93:              {
  94:                  return false;
  95:              }
  96:   
  97:              return typesToSerialize.Contains(property.PropertyType);
  98:          }
  99:   
 100:          private static string GetPropertyString(PropertyInfo property, object instance)
 101:          {
 102:              var propertyValue = property.GetValue(instance, null);
 103:              if (property.PropertyType.IsValueType || propertyValue != null)
 104:              {
 105:                  return propertyValue.ToString();
 106:              }
 107:              return null;
 108:          }
 109:      }
 110:  }

 

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:

   1:  using System;
   2:  using System.Web.Routing;
   3:  using Microsoft.ApplicationServer.Http.Activation;
   4:  using Microsoft.ApplicationServer.Http.Description;
   5:  using NerdDinnerWebApi.ResourceModel;
   6:  using NerdDinnerWebApi.Services.Infrastructure;
   7:  using NerdDinnerWebApi.Services.Services;
   8:   
   9:  [assembly: WebActivator.PreApplicationStartMethod(typeof(NerdDinnerWebApi.Services.App_Start.ServicesInitializer), "Start")]
  10:   
  11:  namespace NerdDinnerWebApi.Services.App_Start
  12:  {
  13:      public static class ServicesInitializer
  14:      {
  15:          public static void Start()
  16:          {
  17:              var iocContainer = StructureMapBootstrapper.Initialize();
  18:              var config = HttpHostConfiguration.Create()
  19:                  .SetResourceFactory(new StructureMapResourceFactory(iocContainer))
  20:                  .AddFormatters(new HalMediaTypeFormatter());
  21:              RouteTable.Routes.MapServiceRoute<DinnerService>("dinners", config);
  22:          }
  23:      }
  24:  }

 

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

   1:  using System;
   2:  using System.Net.Http;
   3:  using System.Net.Http.Headers;
   4:  using Microsoft.ApplicationServer.Http;
   5:  using Microsoft.VisualStudio.TestTools.UnitTesting;
   6:  using NerdDinnerWebApi.ResourceModel;
   7:  using FluentAssertions;
   8:   
   9:  namespace WebApiTests
  10:  {
  11:      [TestClass]
  12:      public class DinnerServiceTests
  13:      {
  14:          private const string baseUri = "http://localhost:1700";
  15:          private static readonly MediaTypeWithQualityHeaderValue halMediaTypeHeader = new MediaTypeWithQualityHeaderValue("application/vnd.nerddinner.hal+xml");
  16:          private static readonly MediaTypeFormatter[] formatters = new[] { new HalMediaTypeFormatter() };
  17:   
  18:          [TestMethod]
  19:          public void Hal_formatter_should_serialize_request_for_dinner_resource()
  20:          {
  21:              // arrange
  22:              var httpClient = new HttpClient(baseUri);
  23:              httpClient.DefaultRequestHeaders.Accept.Add(halMediaTypeHeader);
  24:   
  25:              // act
  26:              var response = httpClient.Get("/dinners/1");
  27:              var dinnerResource = response.Content.ReadAs<Dinner>(formatters);
  28:   
  29:              // assert
  30:              dinnerResource.Should().NotBeNull();
  31:              dinnerResource.Rel.Should().Be("self");
  32:              dinnerResource.HRef.Should().EndWith("/dinners/1");
  33:              dinnerResource.DinnerId.Should().Be(1);
  34:              dinnerResource.Title.Should().Be("MVC Dinner");
  35:              dinnerResource.Description.Should().Be("This dinner will be for MVC developers.");
  36:              dinnerResource.Address.Should().Be("123 Main Street");
  37:              dinnerResource.EventDate.Should().Be(new DateTime(2011, 7, 1));
  38:              dinnerResource.Country.Should().Be("USA");
  39:              dinnerResource.Links.Count.Should().Be(3);
  40:          }
  41:      }
  42:  }

 

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 <Type Name> with the media type <Media Type of Response>.

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.

posted on Monday, June 6, 2011 12:19 AM

Feedback

# re: Understanding Custom WCF Web API Media Type Formatters on Both Server and Client 6/9/2011 12:45 PM Miles
I downloaded the sample and started it in VS 2010. The tests pass however I cannot get the text/html media selector to run for love nor money.

If I test using fiddler, and set the content-type to application/vnd.nerddinner.hal+xml, then the hal media formatter fires, it seems to just to be the html one that's not working. I adjusted the unit test to use the text/html media type, and that confirms the failure...

How can I debug it?


# re: Understanding Custom WCF Web API Media Type Formatters on Both Server and Client 6/10/2011 5:37 AM miles
hey-ho, it all mysteriously started working after a reboot. No idea what had got it in a twist in the first place.

# re: Understanding Custom WCF Web API Media Type Formatters on Both Server and Client 7/9/2011 5:09 AM TarunArora
I like the way u have customized the blog template. can u share how u have added the widgets (linkedIn profile, google search, stackoverflow batch, etc) on the left pane please?
Cheers, Tarun

Post A Comment
Title:
Name:
Email:
Comment:
Verification: