﻿Shoulders of Giants - Web APIRandom development thoughts put out on occasionhttp://shouldersofgiants.co.uk/blog/
http://www.rssboard.org/rss-specificationBlogEngine.NET 2.8.0.2en-GBhttp://shouldersofgiants.co.uk/blog/opml.axdhttp://www.dotnetblogengine.net/syndication.axdPiers LawsonShoulders of Giants0.0000000.000000Deprecating Resources Over MVC<p><a href="http://www.asp.net/mvc" target="_blank">ASP.Net MVC 4</a> has been released and it comes with the <a href="http://www.asp.net/web-api" target="_blank">Web API</a>, a new framework to support HTTP based services. This is what I have been waiting for&hellip; a product from Microsoft that means my <a href="http://rom.codeplex.com/" target="_blank">Resources Over MVC</a> (ROM) project can be deprecated&hellip; or can it?</p>
<p></p>
<p>So what features from ROM can the Web API support and which can&rsquo;t it support (at least out of the box)? Let&rsquo;s look at the features supported by ROM (although more features have been added since, the majority were listed in a <a href="http://www.shouldersofgiants.co.uk/Blog/post/2010/03/27/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-21-e28093-Moving-to-MVC-20.aspx" target="_blank">post</a> written as MVC 2.0 came out).</p>
<h3>Multiple Formats</h3>
<p>Allowing the same resource to be represented in a number of formats is important if you want to enable the widest range of client technologies to use your web service. Way back in my <a href="http://www.shouldersofgiants.co.uk/Blog/post/2008/10/02/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-3-e28093-Multiple-Representations.aspx" target="_blank">third post</a> I first discussed supporting more than one representation. I started with XML, JSON and XHTML then in the <a href="http://www.shouldersofgiants.co.uk/Blog/post/2008/10/08/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-4-e28093-Help-Representation.aspx" target="_blank">fourth post</a> I introduced one more representation, HELP, which would return XHTML with extra documentation and a test harness.</p>
<h5>XML Serialization</h5>
<p>The Web API comes out of the box with JSON and XML support. There is one catch though, the released version defaults to using the Data Contract XML Serializer for XML serialization rather than the much more powerful XmlSerializer. Oddly it does default to using the more powerful JSON.Net for serializing JSON rather than the Data Contract JSON Serializer. I think it odd as the XmlSerializer and JSON.Net both support a very similar set of attributes and naming conventions to allow precise control of the serialization process. For example they both support the incredibly useful (but little known) <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" target="_blank">propertyNameSpecified</a> pattern for setting whether a value should be serialized and indicating whether it has been de-serialized. Luckily, you can switch to using the XmlSerializer by putting the following call in your start up code (e.g. in WebApiConfig):</p>
<p>&nbsp;</p>
<pre class="code"><span style="color: #2b91af;"> GlobalConfiguration</span>.Configuration.Formatters.XmlFormatter.UseXmlSerializer = <span style="color: blue;">true</span>;</pre>
<p>&nbsp;</p>
<p>There is still one slight down side&hellip; the Web API team have not cleaned up the XML that is generated by the XmlSerializer. It will output extra default namespaces resulting in XML such as this being created:</p>
<p>&nbsp;</p>
<p><span style="font-family: Courier New;">&nbsp;&nbsp; &lt;MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xmlns:xsd="http://www.w3.org/2001/XMLSchema" /&gt;</span></p>
<p>&nbsp;</p>
<p>If you don&rsquo;t like these &ldquo;ambient&rdquo; namespaces, perhaps you could vote up my suggestion on the <a href="http://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/3159465-remove-ambient-namespaces-from-serialized-xml" target="_blank">user voice site</a> to allow us to remove them.</p>
<h5>HTML Serialization</h5>
<p>Out of the box the Web API does not have a HTML formatter. In ROM we make use of the standard MVC view handling to provide a powerful way to support HTML representations. <a href="https://github.com/howarddierking/RestBugs/blob/master/RestBugs%20Solution/RestBugs.Services/Formatters/RazorHtmlMediaTypeFormatter.cs" target="_blank">Examples</a> have been written that show how the Razor engine could be hosted to provide a HTML view. However, this hosting mechanism would need to be quite sophisticated if it was to support resolving views and partials as per ASP.Net MVC. This has also been raised on the <a href="http://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/2619955-add-a-html-mediatypeformater-to-the-web-api" target="_blank">user voice site</a>.</p>
<p>I am considering using a different approach, generating the HTML dynamically in much the same way that JSON.Net and the XmlSerializer work&hellip; in other words create an HtmlSerializer that outputs HTML in a consistent manner. This would remove all need for hand written views&hellip; more on this in a future post!</p>
<h5>Help Format</h5>
<p>ROM supports an easy way to provide help / documentation in-line with the API. The content of the help is not auto-generated. The Web API provides an interface (IApiExplorer) that can be used to investigate the resources that are exposed by the API. <a href="http://blogs.msdn.com/b/yaohuang1/archive/2012/08/15/introducing-the-asp-net-web-api-help-page-preview.aspx" target="_blank">Yao</a> has described a downloadable preview of how this interface might be used in the future to automatically generate help pages. I think this will be a powerful feature and a good start has been made. I would like to see it &ldquo;in-line&rdquo; with the API (i.e. responding to the same URIs)&hellip; but this could save a lot of documentation effort.</p>
<h3>Overloading POST</h3>
<p>As discussed in parts <a href="http://www.shouldersofgiants.co.uk/Blog/post/2008/11/07/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-8-e28093-Deleting-a-Resource.aspx" target="_blank">8</a> and <a href="http://www.shouldersofgiants.co.uk/Blog/post/2008/11/09/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-9-e28093-Overloading-POST.aspx" target="_blank">9</a> of my series, there are some user agents that cannot use all the HTTP Verbs we might want to support. For example PUT and DELETE are generally not supported by browsers and when using HTTP Basic Authentication, Flash only allows POST.</p>
<p>One technique often used to circumvent these restrictions is to use a POST, but indicate the actual verb the client wants to use in some other way. This is often called &ldquo;Overloading POST&rdquo;. By part <a href="http://www.shouldersofgiants.co.uk/Blog/post/2009/12/20/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-19-e28093-Baking-in-Method-and-Content-Type-Overloading.aspx" target="_blank">19</a>, ROM supported the following options</p>
<ul>
<li>Add the verb to a request header. By default the web service will check the X-Http-Method-Override header. So the following would cause the web service to perform a delete: ◦X-Http-Method-Override: DELETE</li>
<li>If the request is a FORM post (i.e. it contains key / value pairs used when submitting a form) the web service looks for a FORM variable called X-Http-Method-Override. The value is then used as the verb</li>
<li>The web service also looks for a variable called X-Http-Method-Override in the query string.</li>
</ul>
<p>Out of the box, the Web API does not support Overloading of POST, but it is fairly trivial to implement by deriving a class from DelegatingHandler. In a future post I&rsquo;ll provide an implementation that provides the same functionality supported by ROM.</p>
<h3>Accept Header</h3>
<p>A well behaved HTTP server should inspect the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1" target="_blank">Accept</a> header to decide what format to use when returning a resource representation. The Web API does inspect the Accept header.</p>
<p>Often, for simple user agents, it is necessary to provide other methods for them to dictate the format they want returned. For example, adding <span style="font-family: Courier New;">format=xml</span> to the querystring. ROM added full support for this back in post <a href="http://www.shouldersofgiants.co.uk/Blog/post/2009/12/20/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-19-e28093-Baking-in-Method-and-Content-Type-Overloading.aspx" target="_blank">19</a>. The Web API supports this too. The following added to the application start up (e.g. in the WebApiConfig class) would add the same support:</p>
<pre class="code"><span style="color: #2b91af;"> GlobalConfiguration</span>.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(</pre>
<pre class="code"> <span style="color: blue;">new </span><span style="color: #2b91af;">QueryStringMapping</span>(<span style="color: #a31515;">"format"</span>, <span style="color: #a31515;">"xml"</span>, <span style="color: #a31515;">"application/xml"</span>));</pre>
<p>The one small gripe I have with the Web API&rsquo;s implementation is what it does when the Accept header supplied by the User Agent does not dictate an order of preference for the formats. If more than one of the formats is supported the Web API simply asks each MediaTypeFormatter in turn if it supports one of the acceptable types, and the first one that says yes wins. Ideally I would like to infer an implicit preference for types that have the same quality factor from the order they appear in the header. It is only a small gripe because it appears in the first pass through the formatters, it ignores a */* format. So whereas when a server that supports both XML and JSON receives an Accept header of:</p>
<p><span style="font-family: Courier New;">&nbsp;&nbsp; Accept: application/xml, application/json</span></p>
<p>it might result JSON or XML depending on the order that the formatters were configured server side, a header of:</p>
<p><span style="font-family: Courier New;">&nbsp;&nbsp; Accept: application/xml, */*</span></p>
<p>Will return XML rather than JSON (which in theory could have been returned if the server wanted as */* means the user agent is prepared to accept anything). So in most real world solutions, the Web API will return an appropriate format.</p>
<h3>Accept-Charset</h3>
<p>Another header supported by ROM is the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2" target="_blank">Accept-Charset</a> header that allows the user agent to dictate the character encoding it wants (e.g. utf-16, utf-8 etc.). The Web API supports this header pretty well. There is a known issue that means if the user agent requests an encoding it doesn&rsquo;t understand, rather than returning an HTTP 406 Not Acceptable error, it returns a utf-8 representation. Hopefully this minor issue will be fixed soon.</p>
<h3>Content-Type Header</h3>
<p>The new Web API supports this header&hellip; no problems here!</p>
<h3>Allow Header</h3>
<p>The Allow header (as defined by <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7" target="_blank">RFC-2616</a>) can be used by the web service to indicate which HTTP Verbs are valid against a particular resource. ROM supports this. Currently the Web API does not support it, but it is up on the <a href="http://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/2619986-use-reflection-to-auto-populate-the-allow-header" target="_blank">user voice site</a> for consideration, where you can vote for it to be implemented.</p>
<h3>Areas</h3>
<p>ROM sits on top of ASP.Net MVC and as such it benefits from Area support. The Web API does not support areas which can lead to errors such as:</p>
<blockquote>
<p>Multiple types were found that match the controller named &lsquo;xyz&rsquo;. This can happen if the route that services this request (&lsquo;api/{controller}/{id}&rsquo;) found multiple controllers defined with the same name but differing namespaces, which is not supported.</p>
<p>The request for &lsquo;xyz&rsquo; has found the following matching controllers: MvcApplication.Areas.Abc.Controllers.Api.XyzsController MvcApplication.Controllers.Api.XyzsController</p>
</blockquote>
<p>There are some <a href="http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/" target="_blank">work-arounds</a> suggested out there, but for now there is nothing in the box. It is a shame this isn&rsquo;t supported yet, but I&rsquo;m sure they will address it soon enough&hellip; again it is mentioned of the <a href="http://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/2665576-support-nested-routes" target="_blank">user voice site</a>.</p>
<h3>Conclusion</h3>
<p>I&rsquo;m pretty impressed with the ASP.Net MVC 4 Web API&hellip; it has been a long time coming. I started work on ROM (originally it was just an example shared on this blog) back in <a href="http://www.shouldersofgiants.co.uk/Blog/post/2008/09/27/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-1-Introduction.aspx" target="_blank">September 2008</a>. I always hoped Microsoft would eventually produce something &ldquo;in the box&rdquo;. Four years on, after a few glimpses and false starts, they have. It still needs a few additions before I could use it in place of ROM:</p>
<ul>
<li>A HTML Serializer &ndash; I&rsquo;m going to see what I can do about this</li>
<li>Support for Help &ndash; They are starting on this functionality and hopefully will get there</li>
<li>Overloading POST &ndash; Hopefully I can implement this <!--EndFragment--></li>
</ul>
<p>The good news is, for at least two of these, the extensibility points should allow me to fix them. There are a few &ldquo;nice to haves&rdquo; I hope will be fixed (in descending priority):</p>
<ul>
<li>Cleaned up XML serialization</li>
<li>Support for &ldquo;Areas&rdquo;</li>
<li>Support for the Allow header</li>
<li>Implicit ordering when handling the Accept header</li>
</ul>
<p>So lets see if I can fix two or three things in my top list, then I&rsquo;ll be ready to recommend the deprecation of ROM!</p>http://shouldersofgiants.co.uk/blog/post/2012/09/16/Deprecating-Resources-Over-MVC.aspx
http://shouldersofgiants.co.uk/blog/post/2012/09/16/Deprecating-Resources-Over-MVC.aspx#commenthttp://shouldersofgiants.co.uk/blog/post.aspx?id=8c01921c-379f-4d47-8293-ba96124e1d84Sun, 16 Sep 2012 01:14:00 +0100ASP.Net MVCROMWeb APIAdminhttp://shouldersofgiants.co.uk/blog/pingback.axdhttp://shouldersofgiants.co.uk/blog/post.aspx?id=8c01921c-379f-4d47-8293-ba96124e1d84315http://shouldersofgiants.co.uk/blog/trackback.axd?id=8c01921c-379f-4d47-8293-ba96124e1d84http://shouldersofgiants.co.uk/blog/post/2012/09/16/Deprecating-Resources-Over-MVC.aspx#commenthttp://shouldersofgiants.co.uk/blog/syndication.axd?post=8c01921c-379f-4d47-8293-ba96124e1d84