<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Pedro Félix's shared memory</title>
	<atom:link href="http://pfelix.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://pfelix.wordpress.com</link>
	<description>Conjectures on software</description>
	<lastBuildDate>Fri, 20 Jan 2012 10:31:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='pfelix.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Pedro Félix's shared memory</title>
		<link>http://pfelix.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://pfelix.wordpress.com/osd.xml" title="Pedro Félix&#039;s shared memory" />
	<atom:link rel='hub' href='http://pfelix.wordpress.com/?pushpress=hub'/>
		<item>
		<title>The new System.Net.Http classes: message content</title>
		<link>http://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/</link>
		<comments>http://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 22:54:18 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[HTTP .NET]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=275</guid>
		<description><![CDATA[The 4.5 version of the .NET platform introduces the new System.Net.Http namespace with several HTTP related classes. These classes are also available for .NET 4.0, via the Web API Preview 6 distribution (both&#160;source code&#160;and&#160;NuGet&#160;package). A previous post introduced the HTTP core classes (HttpRequestMessage, HttpResponseMessage and HttpMessageHandler) and described the HttpClient class in detail. This post [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=275&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The 4.5 version of the .NET platform introduces the new <a href="http://msdn.microsoft.com/en-us/library/hh193585(v=VS.110).aspx">System.Net.Http</a> namespace with several HTTP related classes. These classes are also available for .NET 4.0, via the Web API Preview 6 distribution <span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;display:inline!important;font:14px/25px georgia, &#039;white-space:normal;orphans:2;float:none;color:rgb(34,34,34);word-spacing:0;">(both<span class="Apple-converted-space">&#160;</span></span><a style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(0,66,118);word-spacing:0;text-decoration:underline;margin:0;padding:0;" href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">source code</a><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;display:inline!important;font:14px/25px georgia, &#039;white-space:normal;orphans:2;float:none;color:rgb(34,34,34);word-spacing:0;"><span class="Apple-converted-space">&#160;</span>and<span class="Apple-converted-space">&#160;</span></span><a style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(0,66,118);word-spacing:0;text-decoration:underline;margin:0;padding:0;" href="http://nuget.org/packages/HttpClient">NuGet</a><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;display:inline!important;font:14px/25px georgia, &#039;white-space:normal;orphans:2;float:none;color:rgb(34,34,34);word-spacing:0;"><span class="Apple-converted-space">&#160;</span>package). </span></p>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;display:inline!important;font:14px/25px georgia, &#039;white-space:normal;orphans:2;float:none;color:rgb(34,34,34);word-spacing:0;"></span>A <a href="https://pfelix.wordpress.com/2012/01/11/the-new-net-httpclient-class/">previous post</a> introduced the HTTP core classes (<a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a>, <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v=vs.110).aspx">HttpMessageHandler</a>) and described the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class in detail.</p>
<p>This post addresses HTTP message’s content manipulation , and is based on the Web API Preview 6 distribution. Some links point to the MSDN preliminary 4.5 documentation, while others point to the Web API Preview 6 source code; so expect discrepancies. Notice that this post is based on preview code and documentation; the <em>final</em> .NET 4.5 classes may be different of what is described here.</p>
<h3>The HttpContent class</h3>
<p>The content of both request and response messages is access via the <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage.content(v=vs.110).aspx">Content</a> property, of type <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a>.     <br /><a href="http://pfelix.files.wordpress.com/2012/01/httpcontent-2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border-width:0;" title="HttpContent.2" border="0" alt="HttpContent.2" src="http://pfelix.files.wordpress.com/2012/01/httpcontent-2_thumb.png?w=621&#038;h=230" width="621" height="230" /></a></p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a> class contains a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent.headers(v=VS.110).aspx">Headers</a> property, with the content related HTTP headers (e.g. Content-Language, Content-Type, Last-Modified).</p>
<p>It also contains a set of <strong>ReadAsXxx</strong> methods for <em>asynchronously</em> accessing the content body:</p>
<ul>
<li>Task&lt;Stream&gt; <strong>ReadAsStreamAsync</strong>() </li>
<li>Task&lt;byte[]&gt; <strong>ReadAsByteArrayAsync</strong>() </li>
<li>Task&lt;string&gt; <strong>ReadAsStringAsync</strong>() </li>
</ul>
<p>&#160;</p>
<h4>Creating new content</h4>
<p>Reading the message raw content, as a byte sequence or as a string, is accomplished using one of the above methods. However, creating new content involves a hierarchy of concrete classes, rooted at the abstract <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a> class.</p>
<p>&#160;</p>
<p align="center"><a href="http://pfelix.files.wordpress.com/2012/01/httpcontent-untyped-hierarchy.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="HttpContent.untyped.hierarchy" border="0" alt="HttpContent.untyped.hierarchy" src="http://pfelix.files.wordpress.com/2012/01/httpcontent-untyped-hierarchy_thumb.png?w=394&#038;h=632" width="394" height="632" /></a></p>
<p>Each one of those classes support a specific type of content or content source. For instance, producing a string based content is accomplished by creating a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent(v=vs.110).aspx">StringContent</a> instance, parameterized with the string content, the character encoding, and the <a href="http://www.iana.org/assignments/media-types/index.html">media type</a>.</p>
<h3>Typed Content</h3>
<p>The <a href="http://msdn.microsoft.com/en-us/library/hh193585(v=VS.110).aspx">System.Net.Http</a> namespace also contains a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> class for representing <em>strongly typed</em> content, i.e., content based on a strongly typed object.</p>
<p>As depicted in the following diagram, the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> derives from <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a>.&#160; There is also a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent&lt;T&gt;</a> deriving from <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a>, which uses a generic parameter instead of a Type instance to represent the content’s type.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/typedcontent.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border-width:0;" title="TypedContent" border="0" alt="TypedContent" src="http://pfelix.files.wordpress.com/2012/01/typedcontent_thumb.png?w=639&#038;h=769" width="639" height="769" /></a></p>
<p>&#160;</p>
<p>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> is used differently when reading content or producing content.</p>
<h4>Reading strongly typed content</h4>
<p>When reading strongly typed content, an <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> instance is created from a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a> and a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fFormatting%2fMediaTypeFormatter.cs">MediaTypeFormatter</a> is used to convert the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">HttpContent’s</a> stream into the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent’s</a> object.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/stream-formatter-t.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border-width:0;" title="Stream.formatter.T" border="0" alt="Stream.formatter.T" src="http://pfelix.files.wordpress.com/2012/01/stream-formatter-t_thumb.png?w=534&#038;h=130" width="534" height="130" /></a></p>
<p>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fHttpContentExtensionMethods.cs">HttpContentExtensionMethods</a> class contains extension methods to do this</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/contentextensions.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border-width:0;" title="ContentExtensions" border="0" alt="ContentExtensions" src="http://pfelix.files.wordpress.com/2012/01/contentextensions_thumb.png?w=643&#038;h=228" width="643" height="228" /></a></p>
<p>For instance, the <strong>ReadAsAsync</strong> method performs the following </p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:409af590-5a46-432a-8aaa-68bc2a7a30ea" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
public static Task ReadAsAsync(this HttpContent content)
{
    if (content == null)
    {
        throw new ArgumentNullException("content");
    }
    return BuildObjectContent(content).ReadAsAsync();
}

private static ObjectContent BuildObjectContent(HttpContent content)
{
    ObjectContent objectContent = content as ObjectContent;
    if (objectContent == null)
    {
        objectContent = new ObjectContent(content);
    }
    return objectContent;
}
</pre>
</pre>
</div>
<p>Note that reading strongly typed content involves two contents:</p>
<ul>
<li>The original message content, exposed as a byte stream. </li>
<li>The object content, containing an object obtained from the above stream. </li>
</ul>
<p>&#160;</p>
<h4>Producing strongly typed content</h4>
<p>Producing strongly typed content is simpler: just create a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> (or <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent&lt;T&gt;</a>) instance, passing in the object. Since, <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> derives from <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a>, this new instance can be directly used as a message content. Internally, a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fFormatting%2fMediaTypeFormatter.cs">MediaTypeFormatter</a> is used to convert from the typed object into a stream (e.g. when a request message is serialized “to the wire”).</p>
<p>&#160;</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/t-formatter-stream.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border-width:0;" title="T.Formatter.stream" border="0" alt="T.Formatter.stream" src="http://pfelix.files.wordpress.com/2012/01/t-formatter-stream_thumb.png?w=419&#038;h=129" width="419" height="129" /></a></p>
<p>Notice that the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fFormatting%2fMediaTypeFormatter.cs">MediaTypeFormatter</a> class is used for bidirectional conversion:</p>
<ul>
<li>From a byte stream into a typed object. </li>
<li>From a typed object into a byte stream. </li>
</ul>
<p>This class will be the subject of a future post.</p>
<h3>Final remarks</h3>
<ul>
<li>Abstract <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a> base class for representing <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> message content. Contains a set of methods for reading the content’s body as a byte sequence or a string. </li>
<li>Concrete <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.110).aspx">HttpContent</a>-derived classes for creating content. </li>
<li><a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent</a> and <a href="http://wcf.codeplex.com/SourceControl/changeset/view/ee192ebdfb80#WCFWebApi%2fsrc%2fMicrosoft.Net.Http.Formatting%2fSystem%2fNet%2fHttp%2fObjectContent.cs">ObjectContent&lt;T&gt;</a> classes for reading and creating HTTP message body content from strongly typed objects. </li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/275/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/275/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/275/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/275/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/275/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/275/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/275/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/275/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=275&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/httpcontent-2_thumb.png" medium="image">
			<media:title type="html">HttpContent.2</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/httpcontent-untyped-hierarchy_thumb.png" medium="image">
			<media:title type="html">HttpContent.untyped.hierarchy</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/typedcontent_thumb.png" medium="image">
			<media:title type="html">TypedContent</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/stream-formatter-t_thumb.png" medium="image">
			<media:title type="html">Stream.formatter.T</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/contentextensions_thumb.png" medium="image">
			<media:title type="html">ContentExtensions</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/t-formatter-stream_thumb.png" medium="image">
			<media:title type="html">T.Formatter.stream</media:title>
		</media:content>
	</item>
		<item>
		<title>The new .NET HttpClient class</title>
		<link>http://pfelix.wordpress.com/2012/01/11/the-new-net-httpclient-class/</link>
		<comments>http://pfelix.wordpress.com/2012/01/11/the-new-net-httpclient-class/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 13:28:06 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[HTTP .NET]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=256</guid>
		<description><![CDATA[A recent post by Darrel Miller, entitled &#8220;HttpClient, it lives, and it is glorious.&#8221; motivated me to investigate more about the HttpClient class underlying architecture. This post is the result of that study, and focus mainly on design and organization aspects, namely extensibility. For code examples, refer to Darrel&#8217;s excellent post. Introduction The HttpClient class [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=256&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A recent post by <a href="http://www.bizcoder.com/index.php/about/">Darrel Miller</a>, entitled <a href="http://www.bizcoder.com/index.php/2012/01/09/httpclient-it-lives-and-it-is-glorious/" target="_blank">&#8220;HttpClient, it lives, and it is glorious.&#8221;</a> motivated me to investigate more about the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class underlying architecture.<br />
This post is the result of that study, and focus mainly on design and organization aspects, namely extensibility.<br />
For code examples, refer to <a href="http://www.bizcoder.com/index.php/2012/01/09/httpclient-it-lives-and-it-is-glorious/">Darrel&#8217;s excellent post</a>.</p>
<h3>Introduction</h3>
<p>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class is the .NET (yet another) new client for the HTTP protocol, similar in purpose to <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient(v=VS.100).aspx">WebClient</a>. It is being introduced with <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx">.NET 4.5</a>, however there is also an implementation for .NET 4.0 associated with Web API (both <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">source code</a> and <a href="http://nuget.org/packages/HttpClient">NuGet</a> package).</p>
<p>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class should not be viewed in isolation or as just a replacement for <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient(v=VS.100).aspx">WebClient</a>. It is part and takes advantage of a set of new classes for the HTTP protocol, present in the <a href="http://msdn.microsoft.com/en-us/library/hh193585(v=VS.110).aspx">System.Net.Http</a> namespace, which are the subject of the next section.</p>
<h3>Core <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> Abstractions</h3>
<p>The HTTP protocol is an application level request-response protocol that operates by exchanging messages. The new <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage(v=vs.110).aspx">HttpResponseMessages</a> framework classes are used to represent these messages. A <a href="https://pfelix.wordpress.com/2011/04/23/wcf-web-apihttp-message-classes/">previous post</a> described these classes on the Web API context. However, they are used outside of that context, namely on the client side.</p>
<p>The computation that produces response messages, given request messages, is represented by the abstract <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v=vs.110).aspx">HttpMessageHandler</a> class. To avoid blocking the calling thread, this computation signature is asynchronous, that is, a <strong>Task&lt;HttpResponseMessage&gt;</strong> is returned instead of a <strong>HttpResponseMessage</strong>. The <a href="https://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/">&#8220;WCF Web API–Message Handlers&#8221;</a> post described this new class in the Web API context. However this new class is not used exclusively by the Web API. Namely, similarly to <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> and <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a>, this new class is in the <a href="http://msdn.microsoft.com/en-us/library/hh193585(v=VS.110).aspx">System.Net.Http</a> and not on a Web API namespace.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/request-handler-response.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border:0;" title="request.handler.response" src="http://pfelix.files.wordpress.com/2012/01/request-handler-response_thumb.png?w=373&#038;h=138" alt="request.handler.response" width="373" height="138" border="0" /></a></p>
<p>Frequently, messages handlers delegate the response computation to other handlers. Consider, for example, a caching <em>intermediary</em>. If a response to a request can be produced from cached information, then the caching intermediary produces the response directly. Otherwise, the caching <em>component</em> forwards the request message to another handler and caches the response information.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/delegating-handler.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border:0;" title="delegating.handler" src="http://pfelix.files.wordpress.com/2012/01/delegating-handler_thumb.png?w=607&#038;h=137" alt="delegating.handler" width="607" height="137" border="0" /></a></p>
<p>The class <a href="http://msdn.microsoft.com/en-us/library/system.net.http.delegatinghandler(v=vs.110).aspx">DelegatingHandler</a> is used to represent this particular kind of response computation, where the forwarding handler reference is stored on an <strong>InnerHandler</strong> property.</p>
<h3><a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> Architecture</h3>
<p>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class is used to create HTTP request messages, manage the request-response process and extract the response&#8217;s content. However, it delegates the actual sending of the request and the asynchronous response reception to a message handler.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/httpclientandinnerhandler.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border:0;" title="HttpClientAndInnerHandler" src="http://pfelix.files.wordpress.com/2012/01/httpclientandinnerhandler_thumb.png?w=420&#038;h=184" alt="HttpClientAndInnerHandler" width="420" height="184" border="0" /></a></p>
<p>Given the usage of a message handler, the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class may seem redundant. Namely, it is possible to explicitly create a request and use a message handler to obtain a response. However, the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class adds some relevant functionality:</p>
<ul>
<li>Set of helper methods that create requests and also process the responses (e.g. <strong>public Task&lt;string&gt; GetStringAsync(string requestUri)</strong>).</li>
<li>Definition of a default header set, that is applied to all sent messages (<strong>DefaultRequestHeaders</strong> property).</li>
<li>Timeout and cancellation management (e.g. <strong>Timeout</strong> property and <strong>CancelPendingRequests()</strong> method).</li>
</ul>
<p>The .NET framwork provides two message handlers classes, that can be used with the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> for sending requests: the <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler(v=vs.110).aspx">HttpClientHandler</a> class and the <a href="http://msdn.microsoft.com/en-us/library/system.net.http.webrequesthandler(v=vs.110).aspx">WebRequestHandler</a> class. They both use the old <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> internally. The major difference is that <a href="http://msdn.microsoft.com/en-us/library/system.net.http.webrequesthandler(v=vs.110).aspx">WebRequestHandler</a> exposes <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> functionality that isn&#8217;t available in all platforms (e.g. the <strong>Pipelined</strong> property is not available on Silverlight). On the other hand, <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler(v=vs.110).aspx">HttpClientHandler</a> should be usable on all platforms.</p>
<p>The handler used by a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> instance is defined in its constructor. If  absent, a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler(v=vs.110).aspx">HttpClientHandler</a> instance is used by default.<br />
A common technique is to explicitly create a client handler (e.g. <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a>), then explicitly set some of its properties and finally use it to create a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> instance. Darrel’s  <a href="http://www.bizcoder.com/index.php/2012/01/09/httpclient-it-lives-and-it-is-glorious/">Windows authentication example</a>  is an example of this technique.</p>
<p>The following diagram presents the relation between these classes.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/httpclient.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border:0;" title="HttpClient" src="http://pfelix.files.wordpress.com/2012/01/httpclient_thumb.png?w=694&#038;h=646" alt="HttpClient" width="694" height="646" border="0" /></a></p>
<p>Note that this architecture allows the composition of intermediary delegating handlers (e.g. client side caching), resulting in a handler pipeline.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/01/httpclientandhandlerpipeline.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;margin-right:auto;padding-top:0;border:0;" title="HttpClientAndHandlerPipeline" src="http://pfelix.files.wordpress.com/2012/01/httpclientandhandlerpipeline_thumb.png?w=509&#038;h=124" alt="HttpClientAndHandlerPipeline" width="509" height="124" border="0" /></a></p>
<h3>Conclusions</h3>
<p>In conclusion,</p>
<ul>
<li>The new <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class for client side HTTP processing, which is a part of the new <a href="http://msdn.microsoft.com/en-us/library/hh193585(v=VS.110).aspx">System.Web.Http</a> namespace.</li>
<li>Architecture based on message handlers.</li>
<li>Two concrete handlers:   <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler(v=vs.110).aspx">HttpClientHandler</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.http.webrequesthandler(v=vs.110).aspx">WebRequestHandler</a>.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/256/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=256&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/01/11/the-new-net-httpclient-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/request-handler-response_thumb.png" medium="image">
			<media:title type="html">request.handler.response</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/delegating-handler_thumb.png" medium="image">
			<media:title type="html">delegating.handler</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/httpclientandinnerhandler_thumb.png" medium="image">
			<media:title type="html">HttpClientAndInnerHandler</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/httpclient_thumb.png" medium="image">
			<media:title type="html">HttpClient</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/httpclientandhandlerpipeline_thumb.png" medium="image">
			<media:title type="html">HttpClientAndHandlerPipeline</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF Web API&#8211;building an Authorize attribute</title>
		<link>http://pfelix.wordpress.com/2011/10/08/wcf-web-apibuilding-an-authorize-attribute/</link>
		<comments>http://pfelix.wordpress.com/2011/10/08/wcf-web-apibuilding-an-authorize-attribute/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 00:14:19 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/10/08/wcf-web-apibuilding-an-authorize-attribute/</guid>
		<description><![CDATA[This is the thirteenth post&#160;on a&#160;series&#160;about the WCF Web API Preview 4 and 5. &#160;Last post&#160;focused on custom operation parameter conversion. This post shows how to also use operation handlers to build something similar to ASP.NET MVC’s AuthorizeAttribute. The goal is to have an attribute to annotate operations with authorization requirements, such as the illustrated [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=229&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">This is the thirteenth post<span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span">on a<span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a><span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span>about the WCF Web API Preview 4 and 5. <span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><span class="Apple-converted-space">&#160;</span><a href="https://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/">Last post</a><span class="Apple-converted-space">&#160;</span>focused on custom operation parameter conversion. This post shows how to also use operation handlers to build something similar to ASP.NET MVC’s <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx">AuthorizeAttribute</a>.</span></span></span></p>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">The goal is to have an attribute to annotate operations with authorization requirements, such as the illustrated by the following excerpt.</span></span></span></p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:92dfa196-0239-4ba2-9444-950360b1394e" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
[ServiceContract]
class TheService
{
    [Authorize(&quot;Alice&quot;)]
    [WebGet(UriTemplate=&quot;&quot;)]
    HttpResponseMessage Get(...)
    {
		...
    }
}
</pre>
</pre>
</div>
<p>Notice the <strong>[Authorize(“Alice”)]</strong> requiring the request’s user to have the “Alice” identity name.</p>
<p>WCF Web API doesn’t have <a href="http://www.asp.net/mvc/tutorials/understanding-action-filters-cs">MVC’s filters</a>. However, it is possible to have a similar behavior using operation handlers. The following figure shows the overall idea.</p>
<p><a href="http://pfelix.files.wordpress.com/2011/10/authorize.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="Authorize" border="0" alt="Authorize" src="http://pfelix.files.wordpress.com/2011/10/authorize_thumb.png?w=719&#038;h=283" width="719" height="283" /></a></p>
<p>&#160;</p>
<ul>
<li>The <strong>EnableAuthorizeAttribute</strong> configuration extension method checks if the operation’s description contains any <strong>AuthorizeAttribute</strong>. If so, it adds a <strong>AuthorizeOperationHandler</strong> instance to the operation handler pipeline. This instance receives the user identity extracted from the <strong>AuthorizeAttribute</strong>.</li>
<li>The <strong>AuthorizeOperationHandler</strong> declares one input parameter, of type <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx"><strong>IPrincipal</strong></a>. During the request processing, this handler checks if the input principal has the same identity as the one extracted from the <strong>AuthorizeAttribute</strong>. If not, it terminates the request before it reaches the operation, by throwing an <strong>HttpResponseException</strong>.</li>
<li>Notice that the <strong>AuthorizeOperationHandler</strong> is completely decoupled from the authentication process. The authorization’s only dependency is on a principal <em>injected</em> as a parameter.</li>
<li>If the operation doesn’t have a <strong>AuthorizeAttribute</strong>, then no <strong>AuthorizationOperationHandler</strong> is added to its pipeline.</li>
<li>Notice that the end developer only has to annotate the operations with the <strong>AuthorizeAttribute</strong> and call the <strong>EnableAuthorizeAttribute</strong> over the configuration, to enable this behavior.</li>
</ul>
<p>Finally, the (draft) code is available at <a href="https://github.com/pmhsfelix/WcfWebApi.Preview5.Explorations"><font color="#0066cc">https://github.com/pmhsfelix/WcfWebApi.Preview5.Explorations</font></a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/229/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=229&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/10/08/wcf-web-apibuilding-an-authorize-attribute/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/10/authorize_thumb.png" medium="image">
			<media:title type="html">Authorize</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF Web API&#8211;Custom parameter conversion</title>
		<link>http://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/</link>
		<comments>http://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 17:12:20 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/</guid>
		<description><![CDATA[This is the twelfth post&#160;on a&#160;series&#160;about the WCF Web API Preview 4 and 5 releases. Last post focused on operation handlers. The present post shows how to use this handler type to perform custom operation parameter conversion. &#160; Operation parameters On a WCF Web API operation, the URI template variables can be injected as operation’s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=220&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">This is the twelfth post<span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span">on a<span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a><span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span>about the WCF Web API Preview 4 and 5 releases. <a href="https://pfelix.wordpress.com/2011/08/13/wcf-web-apioperation-handlers/">Last post</a> focused on operation handlers. The present post shows how to use this handler type to perform custom operation parameter conversion.</span></span></p>
<h2>&#160;</h2>
<h2>Operation parameters</h2>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span">On a WCF Web API operation, the URI template <a href="http://msdn.microsoft.com/en-us/library/system.uritemplatematch.boundvariables.aspx">variables</a> can be injected as operation’s parameters. The following code excerpt shows a typical example, where the resource identifier (an integer) is obtained from the URI and used as a parameter.</span></span></p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:4d83101a-c9bf-4884-b34c-f42e733e69d5" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
[WebGet(UriTemplate = &quot;{id}&quot;)]
public HttpResponseMessage&lt;Contact&gt; Get(int id){...}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>As stated in a <a href="https://pfelix.wordpress.com/2011/08/13/wcf-web-apioperation-handlers/">previous post</a>, these parameters are retrieved from the URI template match result and added into the operation parameter collection by the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDispatcher%2fUriTemplateHandler.cs">UriTemplateHandler</a> handler. However, this handlers outputs these parameters <em>as strings</em><em>. </em>What if the operation expects a different type, such as the integer id used in the above example? Web API runtime knows how to convert these strings into other types, such as integers. However it doesn’t support user-defined types. For instance, consider the following example, using the user-defined <strong>AComplexType</strong> and <strong>AnotherComplexType</strong> types.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a5a0059c-8b48-441e-83ff-959c94a3b2a0" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
class AComplexType
{
    public string Value { get; set; }
}
class AnotherComplexType
{
    public int Value { get; set; }
}

[WebGet(UriTemplate = &quot;{prm1}/{prm2}&quot;)]
HttpResponseMessage Get(AComplexType prm1, AnotherComplexType prm2)
{
...
}
</pre>
</pre>
</div>
<p>How is it possible to define the conversion from string into <strong>AComplexType</strong> and <strong>AnotherComplexType,</strong> and have it done before the operation is called? </p>
<p>One way of doing this is by using custom operation handlers that:</p>
<ul>
<li>receives <strong>prm1</strong> and <strong>prm2</strong> as strings;</li>
<li>outputs them as <strong>AComplexType</strong> and <strong>AnotherComplexType</strong>.</li>
</ul>
<p>The following handler does exactly this for a generic <strong>T</strong> type:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:c8f1cb3e-a3ee-4e06-98da-73851b7fa92e" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
public class ParameterConversionOperationHandler&lt;T&gt; : HttpOperationHandler
{
    private readonly HttpOperationDescription _desc;
    private readonly Func&lt;string, T&gt; _conv;

    public ParameterConversionOperationHandler(HttpOperationDescription desc, Func&lt;string, T&gt; conv)
    {
        _desc = desc;
        _conv = conv;
    }

    protected override IEnumerable&lt;HttpParameter&gt; OnGetInputParameters()
    {
        return _desc.InputParameters
            .Where(prm =&gt; prm.ParameterType == typeof(T))
            .Select(prm =&gt; new HttpParameter(prm.Name, typeof(string)));
    }

    protected override IEnumerable&lt;HttpParameter&gt; OnGetOutputParameters()
    {
        return _desc.InputParameters
            .Where(prm =&gt; prm.ParameterType == typeof(T));
    }

    protected override object[] OnHandle(object[] input)
    {
        var res = new object[input.Length];
        for (var i = 0; i &lt; input.Length; ++i)
        {
            res[i] = _conv(input[i] as string);
        }
        return res;
    }
 }
</pre>
</pre>
</div>
<p>&#160;</p>
<ul>
<li>The constructor receives a <strong>Func&lt;string, T&gt;</strong>, i.e. a function that converts a string into a <strong>T</strong>. </li>
<li>The <strong>OnGetInputParameters</strong> finds all the operation’s parameters that have type <strong>T</strong> and returns them as <strong>string</strong> input parameters. This means that the Web API runtime will input string parameters into the handler, when processing a request.</li>
<li>Finally, the <strong>OnHandle</strong> method uses the conversion function (<strong>Func&lt;string,T&gt;</strong>) to convert all the input string values into <strong>T</strong> output values. </li>
</ul>
<h2>&#160;</h2>
<h2>Handler registration</h2>
<p>The final step is to add an instance of this handler, into the request handlers collection, for each custom type <strong>T</strong> that we want to be converted. One way of achieving this is by extending&#160; the new Preview 5 configuration model. The following code fragment shows its usage</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:4d6c5a59-f266-4013-9eec-3d7cae9cbd3c" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
var config = new HttpConfiguration()
                .UseParameterConverterFor&lt;AComplexType&gt;(
                    s =&gt; new AComplexType {Value = s.ToUpper()})
                .UseParameterConverterFor&lt;AnotherComplexType&gt;(
                    s =&gt; new AnotherComplexType {Value = Int32.Parse(s)+1});

using (var host = new HttpServiceHost(typeof(TheService), config, &quot;http://localhost:8080/&quot;))
{
    ...
}
</pre>
</pre>
</div>
<p>&#160;</p>
<p>The <strong>UseParameterConverterFor</strong> is a <strong>HttpConfiguration</strong> extension method, receiving the target type <strong>T</strong> and the conversion function,&#160; which registers the required operation handler.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a884ffb7-96cc-47d1-917c-4e3c8fab2afc" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
public static class ParameterConversionExtensions
{
    public static HttpConfiguration UseParameterConverterFor&lt;T&gt;(
	    this HttpConfiguration cfg, Func&lt;string, T&gt; conv)
    {
        cfg.AddRequestHandlers((coll, ep, desc) =&gt;
            {
                if (desc.InputParameters.Any(p =&gt; p.ParameterType == typeof (T)))
                {
                    coll.Add(new ParameterConversionOperationHandler&lt;T&gt;(desc, conv));
                }
            });
        return cfg;
    }
}
</pre>
</pre>
</div>
<p>Note the conditional addition to the handlers collections: the handler is only added if the operation has at least one parameter of type <strong>T</strong>.</p>
<p>This extension method uses another <strong>HttpConfiguration</strong> extension method: <strong>AddRequestHandlers</strong>.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:f26724c4-87ad-4520-9fbe-e094f3fca903" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
public static class HttpConfigurationExtensions
{
    public static HttpConfiguration AddRequestHandlers(
	    this HttpConfiguration conf, 
        Action&lt;Collection&lt;HttpOperationHandler&gt;, ServiceEndpoint, HttpOperationDescription&gt; requestHandlerDelegate)
    {
        var old = conf.RequestHandlers;
        conf.RequestHandlers = old == null ? requestHandlerDelegate :
                                        (coll, ep, desc) =&gt;
                                        {
                                            old(coll, ep, desc);
                                            requestHandlerDelegate(coll, ep, desc);
                                        };
        return conf;
    }
}
</pre>
</pre>
</div>
<p>This new method adds the registration of a new configuration action without removing the ones that may already be defined, i.e., allows for the composition of multiple actions by <em>independent</em> extensions.</p>
<h2>Concluding remarks</h2>
<p>Some concluding remarks:</p>
<ul>
<li>Despite all the code shown on this post the user only has to use the <strong>AddParameterConverterFor</strong> configuration extension method. The remaining code is infra-structure that only has to written once.</li>
<li>The code is available at: <a href="https://github.com/pmhsfelix/WcfWebApi.Preview5.Explorations"><font color="#0066cc">https://github.com/pmhsfelix/WcfWebApi.Preview5.Explorations</font></a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/220/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=220&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF Web API&#8211;Operation Handlers</title>
		<link>http://pfelix.wordpress.com/2011/08/13/wcf-web-apioperation-handlers/</link>
		<comments>http://pfelix.wordpress.com/2011/08/13/wcf-web-apioperation-handlers/#comments</comments>
		<pubDate>Sat, 13 Aug 2011 22:30:00 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/08/13/wcf-web-apioperation-handlers/</guid>
		<description><![CDATA[This is the eleventh post&#160;on a&#160;series&#160;about the Preview 4 of WCF Web API. The sixth post, entitled&#160;WCF Web API–Processing Architecture, presented Web API’s runtime architecture, introducing several key architectural elements, namely&#160;message handlers&#160;and&#160;operation handlers. The last post described message handlers in more detail. In this post, the focus goes to operation handlers. Operation handlers Operation handlers [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=214&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">
<p style="line-height:25px;margin:0 0 10px;padding:0;">This is the eleventh post<span class="Apple-converted-space">&#160;</span><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span">on a<span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a><span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span>about the Preview 4 of WCF Web API. The sixth post, entitled<span class="Apple-converted-space">&#160;</span><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">WCF Web API–Processing Architecture</a>, presented Web API’s runtime architecture, introducing several key architectural elements, namely<span class="Apple-converted-space">&#160;</span><em>message handlers</em><span class="Apple-converted-space">&#160;</span>and<span class="Apple-converted-space">&#160;</span><em>operation handlers</em>. The <a href="https://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/">last post</a> described message handlers in more detail. </span><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span">In this post, the focus goes to <em>operation handlers</em>.</span></p>
<p>   <span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><br />
<h2 style="font-size:22px;font-weight:normal;margin:0 0 15px;padding:0;">Operation handlers</h2>
<p style="line-height:25px;margin:0 0 10px;padding:0;"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span">Operation handlers are a WCF Web API extensibility point located after an operation is selected by the dispatcher, but before the operation’s method is called<span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">, as shown in the following diagram.</span></span></p>
<p style="line-height:25px;margin:0 0 10px;padding:0;"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;margin:0;padding:0;" class="Apple-style-span"><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><img style="display:block;float:none;margin-left:auto;margin-right:auto;" src="http://pfelix.files.wordpress.com/2011/04/runtime2.png?w=720" /></span></span></p>
<p>     </span></span></span><br />
<h2>Pipelines</h2>
<p>There is only one message handler pipeline, where each handler can execute before and after the operation’s invocation. However, there are two operation handler pipelines. The first, called the <em>request pipeline</em>, is composed by the operation handlers executed before the operation’s invocation. The second, called the <em>response pipeline</em>, is constituted by the operation handlers executed after the operation’s call. This characteristic is also visible in the above diagram.</p>
<h2>Request pipeline</h2>
<p>As described in the <a href="https://pfelix.wordpress.com/2011/04/19/wcf-web-apielementary-programming-model/">first post</a> of this series, each operation has a set of input parameters, such as the request’s <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpRequestMessage.cs">HttpRequestMessage</a>, URI template variables and others. In the description model, these parameters are represented by the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpParameter.cs">HttpParameter</a> class (see this <a href="https://pfelix.wordpress.com/2011/05/08/wcf-web-apidescription-model/">post</a> for more information)</p>
<p>The main role of the request pipeline, located between the operation dispatcher and the operation’s method call, is to provide all the parameters required for this invocation. Despite the name similarity, there are significant differences between <em>operation</em> handlers and <em>message</em> handlers:</p>
<ul>
<li>A message handler receives a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpRequestMessage.cs">HttpRequestMessage</a>. An operation handler receives a set of <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpParameter.cs">HttpParameters</a>, dynamically defined at startup.</li>
<li>A message handler <em>asynchronously</em> produces an <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a>, by returning a <strong>Task&lt;HttpResponseMessage&gt;</strong>, which is typically completed <em>after</em> the operation was invoked. A request operation handler <em>synchronously</em> returns a set of <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpParameter.cs">HttpParameter</a>,&#160; <em>before</em> the operation is invoked. This <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpParameter.cs">HttpParameter</a> set is also dynamically defined at startup.</li>
<li>A message handler can completely ignore the inner message handler, short-circuiting the operation’s invocation, and producing an <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a> directly. The only way for an operation handler to short-circuit the call to the operation is by throwing an exception.</li>
</ul>
<h2>Defining operation handlers</h2>
<p>An operation handler is defined by a class derived from <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDispatcher%2fHttpOperationHandler.cs">HttpOperationHandler</a>, as shown in the following code excerpt</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:4e49574d-7478-4057-a40b-bf089412d5f0" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
class LoggingOperationHandler : HttpOperationHandler
{
    protected override IEnumerable&lt;HttpParameter&gt; OnGetInputParameters()
    {
		...
    }

    protected override IEnumerable&lt;HttpParameter&gt; OnGetOutputParameters()
    {
		...
    }

    protected override object[] OnHandle(object[] input)
    {
		...
    }
}
</pre>
</pre>
</div>
<p>The <strong>OnGetInputParameters</strong> method returns a sequence of <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpParameter.cs">HttpParameter</a>, defining the parameters that must be provided to the handler, i.e., the parameter names and types.</p>
<p>The <strong>OnGetOutputParameters</strong> method returns a sequence of <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpParameter.cs">HttpParameter</a>, defining the parameters that are provided by the handler. </p>
<p>The above two methods are called only once, at startup. The third method, <strong>OnHandle</strong>, is called per request. It receives the input parameter values, declared by <strong>OnGetInputParameters</strong>, and returns the output parameter values, declared by <strong>OnGetOutputParameters</strong>.</p>
<p>Since the operation handler’s contract is dynamically defined by the two first methods, and not defined at compile time, the input and output type is <strong>object</strong>. However, WCF Web API contains a set of generic classes, such as <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDispatcher%2fHttpOperationHandler.cs">HttpOperationHandler&lt;T, TOutput&gt;</a>, where the input and output types are statically defined and the <strong>OnGetXxxxParameters</strong> methods are already implemented.</p>
<p><a href="http://pfelix.files.wordpress.com/2011/08/generichttpoperationhandler.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="GenericHttpOperationHandler" border="0" alt="GenericHttpOperationHandler" src="http://pfelix.files.wordpress.com/2011/08/generichttpoperationhandler_thumb.png?w=689&#038;h=329" width="689" height="329" /></a></p>
<h2>Built-in operation handlers</h2>
<p>WCF Web API uses the operation handler extensibility point to provide the parameters typically used by an operation. This is done by a set of built-in operation handlers, namely:</p>
<ul>
<li>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDispatcher%2fUriTemplateHandler.cs">UriTemplateHandler</a> receives a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpRequestMessage.cs">HttpRequestMessage</a> and returns the extracted URI templates variables for the operation.</li>
<li>The <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDispatcher%2fRequestContentHandler.cs">RequestContentHandler</a> receives a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpRequestMessage.cs">HttpRequestMessage</a> and returns a typed <a href="https://pfelix.wordpress.com/2011/05/07/http-content-classes/">HttpRequestMessage</a>, using a <strong>MediaTypeDecoder</strong>&#160; to convert from the content bytes into an object.</li>
</ul>
<h2>Example: tracing the parameter values</h2>
<p>The following code excerpt shows a demo operation handler that inserts all the input parameters into the trace output.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:ec37bd42-7c8d-4896-bfc2-ae7d0283e02c" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
class LoggingOperationHandler : HttpOperationHandler
{
    private readonly HttpParameter[] _prms;
    public LoggingOperationHandler(HttpOperationDescription desc)
    {
        _prms = desc.InputParameters.ToArray();
    }

    protected override IEnumerable&lt;HttpParameter&gt; OnGetInputParameters()
    {
        return _prms;
    }

    protected override IEnumerable&lt;HttpParameter&gt; OnGetOutputParameters()
    {
        yield break;
    }

    protected override object[] OnHandle(object[] input)
    {
        TraceInputs(input);
        return new object[0];
    }

    private void TraceInputs(object[] input)
    {
        var sb = new StringBuilder(&quot;# begin inputs trace #\n&quot;);
        for (int i = 0; i &lt; _prms.Length; ++i)
        {
            sb.AppendFormat(&quot;  {0} : {1}\n&quot;, _prms[i].Name, input[i]);
        }
        sb.AppendLine(&quot;\n# end inputs trace #&quot;);
        Trace.Write(sb.ToString());
    }
}
</pre>
</pre>
</div>
<p>Notice the following:</p>
<ul>
<li>This handler receives exactly the same parameters as the operation’s method. This is accomplished by using the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDescription%2fHttpOperationDescription.cs">HttpOperationDescription</a> to&#160; obtain this information and return it on the <strong>OnGetInputParameters</strong>.</li>
<li>This handler has no output parameters.</li>
<li>The <strong>OnHandle</strong> method receives the operation’s input parameter values and writes them into the trace output.</li>
<li>Since the input parameter collection is not known in compile time, this operation handler derives directly from <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fDispatcher%2fHttpOperationHandler.cs">HttpOperationHandler</a> and not from one of the generic overloads.</li>
</ul>
<h2>Example: extracting the user’s identity and add it as a parameter</h2>
<p>The following code excerpt shows another example of an operation handler. This one extracts the user’s identity from the request’s headers, creates an <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx">IPrincipal</a> and adds it as an parameter.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:1549d03f-0da7-44e7-8a57-07d0019176da" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
class PrincipalFromBasicAuthenticationOperationHandler : HttpOperationHandler&lt;HttpRequestMessage,IPrincipal&gt;
{
    public PrincipalFromBasicAuthenticationOperationHandler() : base(&quot;Principal&quot;)
    {
    }

    public override IPrincipal OnHandle(HttpRequestMessage input)
    {
        Console.WriteLine(&quot;PrincipalFromBasicAuthenticationOperationHandler.OnHandle&quot;);
        if (input.Headers.Authorization == null || input.Headers.Authorization.Scheme != &quot;Basic&quot;)
        {
            // If properly configured, this should never happen:
            // this OperationHandler should only be used when 
            // Basic authorization is required
            throw new HttpResponseException(HttpStatusCode.InternalServerError);
        }
        var encoded = input.Headers.Authorization.Parameter;
        var encoding = Encoding.GetEncoding(&quot;iso-8859-1&quot;);
        var userPass = encoding.GetString(Convert.FromBase64String(encoded));
        int sep = userPass.IndexOf(':');
        var username = userPass.Substring(0, sep);
        var identity = new GenericIdentity(username, &quot;Basic&quot;);
        return new GenericPrincipal(identity, new string[] { });
    }
}
</pre>
</pre>
</div>
<p>This class derives from the generic<strong>HttpOperationHandler&lt;HttpRequestMessage,IPrincipal&gt;</strong>, since the input and output are known at compile time. The constructor calls the base constructor defining the output parameter’s name. The <strong>OnHandle</strong> method uses the <strong>Authorization</strong> header to extract the user’s identity, <strong>assuming that it was already validated</strong> (by the WCF runtime or by a message handler, see this <a href="https://pfelix.wordpress.com/2011/04/21/wcf-web-api-self-hosting-https-and-http-basic-authentication/">post</a>).</p>
<p>Since this handler adds an <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx">IPrincipal</a> as a parameter, now any operation can use this interface as an input parameter</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:ee0d941b-6f78-48cf-9d78-743a66397c76" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
[ServiceContract]
class TheResourceClass
{
    [WebGet(UriTemplate=&quot;resources/{id}&quot;)]
    HttpResponseMessage GetSomething(HttpRequestMessage req, int id, IPrincipal principal)
    {
        ...
    }
}
</pre>
</pre>
</div>
<h2>Operation handler order</h2>
<p>With message handlers, the execution order equals the configuration order. However, with operation handlers things are different. Since there could be handlers that need the output of other handlers, the execution order must satisfy this parameter dependency. </p>
<p>For example, consider an handler that receives an <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx">IPrincipal</a> and uses it to evaluate an authorization policy. This handler must be executed after the above <strong>PrincipalFromBasicAuthenticationOperationHandler</strong>, in order to receive the user’s identity.</p>
<p>On startup, the WCF runtime uses the input and output handler information (via the <strong>OnGetInputParameters/OnGetOutputParameters</strong> methods) to compute a permutation of the configuration order that satisfies the input-output dependencies. If such an order doesn’t exists, an exception is throwed when the service starts.</p>
<p>The following diagram illustrates these dependencies.</p>
<p><a href="http://pfelix.files.wordpress.com/2011/08/operationhandlers2.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="OperationHandlers2" border="0" alt="OperationHandlers2" src="http://pfelix.files.wordpress.com/2011/08/operationhandlers2_thumb.png?w=656&#038;h=352" width="656" height="352" /></a></p>
<h2>Configuration</h2>
<p>The operation handlers can be configured via an operation handler factory, as the one showed in the next code excerpt</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:559c924d-a4e7-45bf-8dc2-b2a2b70b4d27" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
class MyOperationHandlerFactory : HttpOperationHandlerFactory
{
    protected override Collection&lt;HttpOperationHandler&gt; OnCreateRequestHandlers(ServiceEndpoint endpoint, HttpOperationDescription operation)
    {
        var coll = base.OnCreateRequestHandlers(endpoint, operation);
        if (operation.InputParameters.Any(p =&gt; p.Type.Equals(typeof(IPrincipal))))
        {
            var binding = endpoint.Binding as HttpBinding;
            if (binding != null &amp;&amp; binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Basic)
            {
                coll.Add(new PrincipalFromBasicAuthenticationOperationHandler());
            }
        }
        return coll;
    }
}
</pre>
</pre>
</div>
<p>Notice the following:</p>
<ul>
<li>The call to the <strong>base.OnCreateRequestHandlers</strong>, so that the built-in handlers are also included in the collection.</li>
<li>The conditional addition logic, using service description information from the <strong>ServiceEndpoint</strong> and from <strong>HttpOperationDescription</strong>: the <strong>PrincipalFromBasicAuthenticationOperationHandler</strong> is only added if the operation requires an <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx">IPrincipal</a> and the binding is using <strong>HttpClientCredentialType.Basic</strong>.</li>
</ul>
<h2>External resources</h2>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">Finally, here are some interesting references about message handlers:</span></p>
<ul>
<li><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">A <a href="http://blog.alexonasp.net/post/2011/07/26/Look-Ma-I-can-handle-JSONP-(aka-Cross-Domain-JSON)-with-WCF-Web-API-and-jQuery!.aspx">response operation handler for JSONP support</a>, by Alexander Zeitler.</span></li>
<li><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><a href="http://weblogs.asp.net/cibrax/archive/2011/04/19/configuring-your-wcf-web-apis.aspx">Configuring your WCF APIs</a>, by Pablo Cibraro.</span></li>
<li><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><a href="http://codebetter.com/glennblock/2011/05/17/message-handlers-vs-operation-handlers-which-one-to-use-2/">Message Handlers vs Operation Handlers which one to use?</a>, by Glenn Block.</span></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/214/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=214&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/08/13/wcf-web-apioperation-handlers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/04/runtime2.png?w=720" medium="image" />

		<media:content url="http://pfelix.files.wordpress.com/2011/08/generichttpoperationhandler_thumb.png" medium="image">
			<media:title type="html">GenericHttpOperationHandler</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/08/operationhandlers2_thumb.png" medium="image">
			<media:title type="html">OperationHandlers2</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF Web API&#8211;Message Handlers</title>
		<link>http://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/</link>
		<comments>http://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 15:37:38 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/</guid>
		<description><![CDATA[This is the tenth post on a&#160;series&#160;about the Preview 4 of WCF Web API. The sixth post, entitled WCF Web API–Processing Architecture, presented Web API’s runtime architecture, introducing several key architectural elements, namely message handlers and operation handlers. In this post, I describe message handlers in more detail, presenting some examples and a set of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=209&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is the tenth post <span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">on a<span class="Apple-converted-space">&#160;</span><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a><span class="Apple-converted-space">&#160;</span>about the Preview 4 of WCF Web API. The sixth post, entitled <a href="http://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">WCF Web API–Processing Architecture</a>, presented Web API’s runtime architecture, introducing several key architectural elements, namely <em>message handlers</em> and <em>operation handlers</em>.</span></p>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">In this post, I describe message handlers in more detail, presenting some examples and a set of external resources on this subject.</span></p>
<h2>Message handlers</h2>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span">Message handlers are a WCF Web API extensibility point located after a <strong>HttpRequestMessage</strong> is retrieved from the transport channel but before this message is dispatched to an operation, as shown in the following diagram</span></p>
<p><span style="widows:2;text-transform:none;background-color:rgb(255,255,255);text-indent:0;letter-spacing:normal;font:14px/25px georgia, &#039;white-space:normal;orphans:2;color:rgb(34,34,34);word-spacing:0;" class="Apple-style-span"><img src="http://pfelix.files.wordpress.com/2011/04/runtime2.png?w=720" /></span></p>
<p>Message handlers are also located before the operation handlers. This has several consequences:</p>
<ul>
<li>The <em>same</em> message handler instance is used <em>for all</em> the operations, i.e., all request URIs and <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> methods. Namely, the handler doesn’t have access to the dispatching result &#8211; the final operation. However, there are different message handler instances per endpoint. </li>
<li>The message handler only has access to the request message and not to the operation’s parameters. </li>
</ul>
<p>Message handlers use a “<a href="http://en.wikipedia.org/wiki/Matryoshka_doll">russian-doll</a>” model, also used by <a href="http://codebetter.com/jeremymiller/2011/01/09/fubumvcs-internal-runtime-the-russian-doll-model-and-how-it-compares-to-asp-net-mvc-and-openrasta/">other frameworks</a>:</p>
<ul>
<li>On initialization, each message handler receives a reference to a <em>inner handler</em>. </li>
<li>On request processing, each message handler receives the request and is responsible to produce a response, eventually delegating that task to the <em>inner handler</em> (in Preview 4 message handlers are still called delegating handlers). </li>
</ul>
<p>However, message handlers don’t use a synchronous model. Instead, they use an asynchronous model, based on the <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> class: instead of returning a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a>, a message handler must return a <strong>Task&lt;HttpResponseMessage&gt;</strong>. This means that message handlers are an adequate extension point to insert lengthy I/O requests.</p>
<p>On Preview 4, a message handler is a class that must derive from <strong>DelegatingChannel</strong> and overrides the <strong>SendAsync</strong> method.</p>
<h2>Example: Adding an header with the elapsed time</h2>
<p>The following code excerpt show a simple message channel that records the request’s processing time and adds an header to the response with it. Note how, after creating the <strong>Stopwatch</strong>, the request is simply delegated to the inner handler (<strong>base.SendAsync</strong>)</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2231323a-2de5-4b59-9b5e-ceb7865ae0b7" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: erlang; pad-line-numbers: true;">
class ElapsedTimeMessageHandler : DelegatingChannel
{
    public ElapsedTimeMessageHandler(HttpMessageChannel innerChannel)
        : base(innerChannel)
    {
    }

    protected override Task&lt;HttpResponseMessage&gt; SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var sw = new Stopwatch();
        sw.Start();
        return
            base.SendAsync(request, cancellationToken)
                .ContinueWith(task =&gt;
                    {
                        sw.Stop();
                        task.Result.Headers.Add(&quot;X-Elapsed-Time&quot;, 
						    sw.ElapsedMilliseconds.ToString());
                        return task.Result;
                    },TaskContinuationOptions.ExecuteSynchronously);
    }
}
</pre>
</pre>
</div>
<p>&#160;</p>
<h2>Example: HTTP intermediary</h2>
<p>A message handler doesn’t even need to call the inner handler. Namely, it can completely bypass the upper WCF runtime stack.</p>
<p>The following code excerpt shows a message handler prototype that simply forwards all the HTTP requests to the origin server, using an <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> object. It illustrates a simplistic way of implementing HTTP&#160; intermediaries (e.g. proxies).</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:b146e7b0-f745-483e-9989-5ce9c8c7b51f" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: erlang;">
class ProxyMessageHandler : DelegatingChannel
{
    private readonly HttpClient _client = new HttpClient();
    public ProxyMessageHandler(HttpMessageChannel innerChannel)
        : base(innerChannel)
    {
    }

    protected override Task&lt;HttpResponseMessage&gt; SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        try
        {
            var req = new HttpRequestMessage
                    {
                        RequestUri =
                            new Uri(&quot;http://&quot; + request.Headers.Host + request.RequestUri.PathAndQuery),
                        Method = request.Method
                    };
            if (req.Method == HttpMethod.Post || req.Method == HttpMethod.Put)
            {
                req.Content = request.Content;
            }
            foreach (var h in request.Headers.Where(h =&gt; !h.Key.StartsWith(&quot;Proxy-&quot;)))
            {
                req.Headers.Add(h.Key, h.Value);
            }
            var resp = _client.SendAsync(req,HttpCompletionOption.ResponseHeadersRead);
            resp.ContinueWith(t =&gt; TraceResponse(req,t));
            return resp.ContinueWith(t =&gt;
                {
                    t.Result.Headers.Remove(&quot;Transfer-Encoding&quot;);
                    return t.Result;
                });
        }
        catch (Exception e)
        {
           TraceException(e);
            throw;
        }
    }
}
</pre>
</pre>
</div>
<h2>&#160;</h2>
<h2>Configuration</h2>
<p>Message handlers can be configured via a <strong>HttpHostConfiguration</strong> class and the <strong>AddMessageHandlers</strong> method. This is illustrated in the following code excerpt. Notice that <strong>ProxyMessage</strong> handler is the inner handler of <strong>ElapseTimeMessageHandlers</strong>.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:e41dda75-ae28-406a-b805-bee1306e91bf" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp;">
var cfg = HttpHostConfiguration.Create()
			.AddMessageHandlers(typeof(ProxyMessageHandler), typeof(ElapsedTimeMessageHandler));
	
using (var host = new HttpConfigurableServiceHost(typeof(TheService), cfg, new Uri(...)))
...
</pre>
</pre>
</div>
<h2>External resources</h2>
<p>Finally, here are some interesting references about message handlers:</p>
<ul>
<li><a href="http://weblogs.asp.net/cibrax/archive/2011/04/15/http-message-channels-in-wcf-web-apis-preview-4.aspx">An introduction to message handlers, by Pablo Cibraro, with a very interesting API key verification example</a>.</li>
<li><a href="http://blogs.msdn.com/b/gblock/archive/2011/05/17/message-handlers-vs-operation-handlers-which-one-to-use.aspx">Differentiation between message handlers and operation handlers, by Glenn Block</a>.</li>
<li><a href="http://channel9.msdn.com/Shows/AppFabric-tv/AppFabrictv-Automatic-ETag-Management-with-WCF-Web-API-Message-Handlers">Automatic ETag Management with WCF Web API Message Handlers, on Channel 9</a>.</li>
<li><a href="http://www.bizcoder.com/index.php/2011/05/22/how-to-get-ahead-with-messagehandlers/">Supporting HEAD</a> and <a href="http://www.bizcoder.com/index.php/2011/05/21/http-trace-was-never-so-easy/">TRACE</a>, by <a href="http://www.bizcoder.com/index.php/about/">Darrel Miller</a>.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/209/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/209/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/209/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=209&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/04/runtime2.png" medium="image" />
	</item>
		<item>
		<title>WCF Web API&#8211; Handling requests asynchronously</title>
		<link>http://pfelix.wordpress.com/2011/08/05/wcf-web-api-handling-requests-asynchronously/</link>
		<comments>http://pfelix.wordpress.com/2011/08/05/wcf-web-api-handling-requests-asynchronously/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 16:19:00 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[WCF Web API]]></category>
		<category><![CDATA[TPL]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/08/05/wcf-web-api-handling-requests-asynchronously/</guid>
		<description><![CDATA[This is the ninth post on a series about the Preview 4 of WCF Web API. The previous posts were: Elementary programming model Self-hosting Self-hosting, HTTPS and HTTP Basic Authentication IIS Hosting HTTP Message Classes Processing Architecture HTTP Content Classes Description Model In this post, I show how to handle HTTP requests asynchronously. .NET’s Asynchronous [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=206&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is the ninth post on a <a href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a> about the Preview 4 of WCF Web API. The previous posts were:</p>
<ul>
<li><a href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apielementary-programming-model/">Elementary programming model</a></li>
<li><a href="http://pfelix.wordpress.com/2011/04/20/wcf-web-apiself-hosting/">Self-hosting</a></li>
<li><a href="http://pfelix.wordpress.com/2011/04/21/wcf-web-api-self-hosting-https-and-http-basic-authentication/">Self-hosting, HTTPS and HTTP Basic Authentication</a></li>
<li><a href="http://pfelix.wordpress.com/2011/04/22/wcf-web-apiiis-hosting/">IIS Hosting</a></li>
<li><a href="http://pfelix.wordpress.com/2011/04/23/wcf-web-apihttp-message-classes/">HTTP Message Classes</a></li>
<li><a href="http://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">Processing Architecture</a></li>
<li><a href="https://pfelix.wordpress.com/2011/05/07/http-content-classes/">HTTP Content Classes</a></li>
<li><a href="https://pfelix.wordpress.com/2011/05/08/wcf-web-apidescription-model/">Description Model</a></li>
</ul>
<p>In this post, I show how to handle <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> requests asynchronously.</p>
<h2>.NET’s Asynchronous Programming Model (APM)</h2>
<p>The first version of the .NET platform introduced the <em>Asynchronous Programming Model</em> (APM) to represent asynchronous operations. It is characterized by the following:</p>
<ul>
<li>Each asynchronous operation is divided into two methods, the <strong>Begin</strong> method and the <strong>End</strong> method;</li>
<li>The <strong>Begin</strong> method receives the operation’s inputs and two extra parameters – an <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">AsyncCallback</a> and an object state. This method must return an <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">IAsyncResult</a>, representing the asynchronous operation.</li>
<li>The <strong>End</strong> method receives the above <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">IAsyncResult</a> and returns the operation result, waiting if it is not yet available</li>
</ul>
<p>The APM model is used in several places of the .NET platform. Some examples are stream reading and writing; and asynchronous delegate invocation.</p>
<p>Currently, WCF also uses the APM model both on the client side and on the service side:</p>
<ul>
<li>On the client-side, the generated proxies can expose each WCF operation as a <strong>Begin</strong>/<strong>End</strong> method pair.</li>
<li>On the service-side, the implementing class may expose a <strong>Begin</strong>/<strong>End</strong> method pair that will be called asynchronously by the WCF runtime.</li>
</ul>
<p>The Preview 4 release of WCF Web API also supports this model. The following code excerpt shows an example of decomposing an Web API operation into a <strong>Begin</strong> and <strong>End</strong> methods</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:672d3c71-baf1-4e05-a2f5-86876a0f34f5" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
[OperationContract(AsyncPattern = true)]
[WebGet(UriTemplate = &quot;image?uri={uri}&quot;)]
private IAsyncResult BeginGetImage(HttpRequestMessage req, string uri,
                                                 AsyncCallback ac, object state)
{
	...
}

private HttpResponseMessage EndGetImage(IAsyncResult ar)
{
	...
}
</pre></p>
</div>
<p>The usage of the asynchronous model is defined by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.asyncpattern.aspx">AsyncPattern</a> property assigned with <strong>true</strong> on the <strong>OperationContract</strong> attribute.</p>
<p>More details about the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.asyncpattern.aspx">AsyncPattern</a> in “classical” WCF can be found in the following post series: <a href="http://pfelix.wordpress.com/2008/07/11/wcf-and-the-asyncpattern-property-part-3/">WCF and the AsyncPattern property</a>.</p>
<h2>The Task-based model</h2>
<p>The version 4.0 of .NET introduced a new asynchronous model based on the <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> class and <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx">TPL library</a>. A <strong>Task&lt;T&gt;</strong> represents an asynchronous operation that returns a value of type <strong>T</strong>. On a first look, this class may seem similar to <a href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx">IAsyncResult</a>, however there are significant differences:</p>
<ul>
<li>No need to call an <strong>End</strong> operation to retrieve the result. Instead, this value can be obtained from the task itself.</li>
<li>Better support for cancellation, through <a href="http://msdn.microsoft.com/en-us/library/dd997364.aspx">cancellation tokens</a>.</li>
<li>Better support for exception handling.</li>
<li>Native support for asynchronous operation composition, via the <a href="http://msdn.microsoft.com/en-us/library/dd235663.aspx">ContinueWith</a> and the <a href="http://msdn.microsoft.com/en-us/library/dd321473.aspx">ContinueWhenAll</a>/<a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.continuewhenany.aspx">ContinueWhenAny</a> methods.</li>
</ul>
<p>The announced <a href="http://msdn.microsoft.com/en-us/vstudio/gg316360">C#async support</a> is also based on the <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> model and will provide a language integrated way of building and composing asynchronous operations.</p>
<p>In the .NET framework, this new <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> model is slowly replacing the APM model. For instance:</p>
<ul>
<li>The new .NET’s HTTP client (<a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient class</a>) provides a set of <strong>XxxAsync</strong> methods, returning <strong>Task&lt;HttpResponseMessage&gt;</strong>, for performing asynchronous HTTP requests.</li>
<li>The WCF Web API message handlers, briefly described in the <a href="https://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">sixth post of this series</a>, also use the new Task&lt;T&gt; model.</li>
</ul>
<h2>Using both asynchronous models</h2>
<p>Unfortunately, the Preview 4 of WCF Web API doesn’t yet support the <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> model for the operation implementation. However, it is not hard to implement a APM based interface using <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a>, as described in the following reference: <a href="http://msdn.microsoft.com/en-us/library/dd997423.aspx">TPL and Traditional .NET Asynchronous Programming</a>. The key fact is that the <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> class also implements the <a href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx">IAsyncResult</a> interface.</p>
<h2>An example</h2>
<p>To exemplify these concepts, the following example shows a service for image transcoding. It has one operation, that handles GET requests on the following URI template “<strong>image?uri={uri}</strong>”, and performs the following actions:</p>
<ul>
<li>GETs the representation of the resource (an image) identified by the <strong>{uri}</strong></li>
<li>Tries to build a bitmap with this resource’s representation</li>
<li>Encodes and returns the bitmap using the JPEG format</li>
</ul>
<p>Obtaining the response to the GET request and all the associated representation bytes may take a significant time. In order to avoid keeping a thread blocked during this time, this operation’s implementation will be asynchronous.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:54bba8bc-e301-4b2c-a288-ddbe71c5f2b3" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
private HttpResponseMessage _response;
private HttpResponseException _exception;

[OperationContract(AsyncPattern = true)]
[WebGet(UriTemplate = &quot;image?uri={uri}&quot;)]
private IAsyncResult BeginGetImage(string uri, AsyncCallback ac, object state)
{
    Trace(&quot;BeginGet...&quot;);
    var task = Task.Factory.Iterate(GetImageAndConvertItToJpeg(uri), state);
    task.ContinueWith(t =&gt;
        {
         Trace(&quot;Main task completed, calling callback&quot;);
         if (ac != null) ac(task);
        }, TaskContinuationOptions.ExecuteSynchronously);
     return task;
}

private HttpResponseMessage EndGetImage(IAsyncResult ar)
{
    Trace(&quot;...EndGet&quot;);
    var task = ar as Task;
    if (task == null || task.IsFaulted)
    {
        throw new HttpResponseException(HttpStatusCode.InternalServerError);
    }
    if (_exception != null) throw _exception;
    return _response;
}
</pre></p>
</div>
<p>The previous code excerpt presents the <strong>BeginGetImage</strong> and <strong>EndGetImage</strong> methods.</p>
<p>Regarding the <strong>Begin</strong> method:</p>
<ul>
<li>The operation core processing is started on line 9, using a iterator based technique described in the following section, and is represented by a task.</li>
<li>On line 10, a continuation is added to the above task, so that the WCF callback is called when the task completes. This will trigger the call, by the WCF runtime, of the <strong>EndGetImage</strong> method.</li>
<li>On line 15, the task created on line 9 is returned. Notice that the operation’s return type is <strong>IAsyncResult</strong>. However, as stated in the beginning of this post, the <strong>Task</strong> class implements <strong>IAsyncResult </strong>interface. This is the key aspect to translate from the <strong>Task</strong> model into the APM model. The other aspect is the use of the <strong>state</strong> parameter when creating the task.</li>
</ul>
<p>Regarding the <strong>End</strong> method:</p>
<ul>
<li>On line 21, the <strong>IAsyncResult</strong> is casted to a task. Notice that, according to the APM, the <strong>IAsyncResult</strong> passed into the <strong>End</strong> method is the one returned by the <strong>Begin</strong> method.</li>
<li>Finally, the <strong>_exception</strong> and <strong>_response</strong> instance fields are consulted to produce an exception or response. These fields are assigned by the asynchronous process started on line 9 of the <strong>Begin</strong> method, as described in the following section.</li>
</ul>
<p>Notice that the above code is rather generic. It could be used to implement other operations, just by changing line 9.</p>
<h2>Using iterators to define asynchronous behavior</h2>
<p>The typical way of defining asynchronous behavior with the <strong>Task&lt;T&gt;</strong> model is by chaining tasks with actions, producing other tasks. This breaks the code into multiple methods/anonymous methods/lambdas, reducing the readability.</p>
<p>In this post, we use an iterator based technique <a href="http://msdn.microsoft.com/en-us/magazine/cc546608.aspx">proposed by J. Richter for the APM</a> and <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/06/30/9809774.aspx">adapted to the Task&lt;T&gt; model by the ParallelExtensionExtras</a>. The following code excerpt shows the asynchronous processing of the <strong>GetImageAndConvertItToJpeg</strong> method, implemented as a C# iterator.</p>
<p>&nbsp;</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a692ca1d-5019-4bb9-9d27-fa6260add9f9" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;"><pre class="brush: csharp;">
private IEnumerable&lt;Task&gt; GetImageAndConvertItToJpeg(string uri)
{
    using (var client = new HttpClient
        {
            MaxResponseContentBufferSize = 1024*1024
        })
    {
        uri = Uri.UnescapeDataString(uri);
        Task&lt;HttpResponseMessage&gt; readTask = null;
        try
        {
            readTask = client.GetAsync(uri);
        }
        catch (Exception)
        {
            _exception = new HttpResponseException(HttpStatusCode.NotFound);
            yield break;
        }
        Trace(&quot;yielding for HTTP response...&quot;);
        yield return readTask;

        Trace(&quot;...resuming after HTTP response completed&quot;);
        if (readTask.IsFaulted || readTask.Result.StatusCode != HttpStatusCode.OK)
        {
            _exception = new HttpResponseException(HttpStatusCode.NotFound);
            yield break;
        }
        var httpContent = readTask.Result.Content;
        using (var ms = new MemoryStream())
        {
            var copyTask = httpContent.ContentReadStream.CopyStreamToStreamAsync(ms);
            Trace(&quot;yielding for stream copy...&quot;);
            yield return copyTask;

            Trace(&quot;...resuming after copy completed&quot;);
            if (copyTask.IsFaulted)
            {
                _exception = new HttpResponseException(HttpStatusCode.NotFound);
                yield break;
            }
            Bitmap bitmap = null;
            try
            {
                bitmap = new Bitmap(ms);
            }
            catch (Exception)
            {
                _exception = new HttpResponseException(HttpStatusCode.NotFound);
                yield break;
            }
            var output = new MemoryStream();
            bitmap.Save(output, ImageFormat.Jpeg);
            output.Seek(0, SeekOrigin.Begin);
            var content = new StreamContent(output);
            content.Headers.ContentType = new MediaTypeHeaderValue(&quot;image/jpeg&quot;);
            _response = new HttpResponseMessage
                {
                    Content = content
                };
        }
    }
}
</pre></p>
</div>
<p>&nbsp;</p>
<p>This code performs the following:</p>
<ul>
<li>An <strong><a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a></strong> is created to retrieve the upstream image. If any exception occurs while creating and starting the request, then the <strong>_exception</strong> instance field is assigned with an <strong>HttpResponseException</strong> and the iterator stops (<strong>yield break</strong>). If not, the result of the <strong>client.GetAsync(uri)</strong> statement is a <strong>Task&lt;HttpResponseMessage&gt;, </strong>representing the HTTP request. This task is then returned by the iterator, <strong>without blocking the hosting thread</strong>.</li>
<li>The iterator is resumed only when this <strong>Task&lt;HttpResponseMessage&gt;</strong> completes. Then it checks for errors, and if everything is ok, creates a task to copy the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a>’s stream into a memory stream. This is done to ensure that all the image’s content are in memory when the bitmap is created. If the bitmap was created directly from the  <strong>HttpResponseMessage</strong>’s stream, then the <strong>Bitmap</strong>constructor would block the hosting thread while waiting for all the bytes (and we don’t want to block threads!).The stream copy uses the <strong>CopyStreamToStreamAsync</strong> extension method, also available on the <a href="http://code.msdn.microsoft.com/ParExtSamples">ParallelExtensionExtras</a>. The task returned by this method is then returned by the iterator, so that the stream copy is performed asynchronously.</li>
<li>The iterator is resumed again when the stream copy completes. After some error checking, the <strong>Bitmap</strong> is finally created and saved into another memory stream used in the response message. Notice that this can be done synchronously, since it doesn’t require any I/O.</li>
</ul>
<p>Unfortunately, the above code is slightly cluttered by the error handling and by the fact that a <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx">yield statement cannot be inside a try-catch block</a>.</p>
<p>The chaining of the tasks returned by the above iterator is done by the <a href="http://code.msdn.microsoft.com/ParExtSamples">ParallelExtensionExtras</a> <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/06/30/9809774.aspx">Iterate</a> method, that wraps the overall resulting asynchronous processing in a Task (remember line 9 of the second code excerpt).</p>
<p>This chaining is performed by the following:</p>
<ul>
<li>When initially called, the <strong>Iterate</strong> method schedules a task, using <strong>StartNew</strong>, that will call the iterator to retrieve the first task. It also creates a <strong>TaskCompletionSource</strong> to represent the  overall task.</li>
<li>The first task retrieved from the iterator (representing the HTTP request) is then chained with another call to the iterator, using a <strong>ContinueWith</strong>.</li>
<li>The second task retrieved from the iterator (representing the stream copy) is also chained with another call to the iterator.</li>
<li>The final call to the iterator doesn’t return any element (<strong>MoveNext</strong> returns false), so <strong>Iterate</strong> signals the <strong>TaskCompletionSource</strong> that all the work is completed. This results in the call of the WCF callback.</li>
</ul>
<p>The following diagram presents a sequence diagram, with the interaction between the different components.</p>
<p><a href="http://pfelix.files.wordpress.com/2011/08/async.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="async" src="http://pfelix.files.wordpress.com/2011/08/async_thumb.png?w=661&#038;h=764" alt="async" width="661" height="764" border="0" /></a></p>
<p>The following color scheme is used:</p>
<ul>
<li>Red – WCF runtime components;</li>
<li>Green – user code (<strong>Iterator</strong> represents the enumerable returned by the <strong>GetImageAndConvertItToJpeg</strong> method);</li>
<li>Light blue – TPL scheduler;</li>
<li>Dark blue – <strong>Iterate</strong> extension method (from the <a href="http://code.msdn.microsoft.com/ParExtSamples">ParallelExtensionExtras</a>)</li>
</ul>
<p>The tracing output one of execution is (the first number is the managed thread id)</p>
<p><span style="font-family:Consolas;">3: BeginGet&#8230;</p>
<p>6: yielding for HTTP response&#8230;</span></p>
<p>9: &#8230;resuming after HTTP response completed</p>
<p>9: yielding for stream copy&#8230;</p>
<p>6: &#8230;resuming after copy completed</p>
<p>6: Main task completed, calling callback</p>
<p>8: &#8230;EndGet</p>
<h2>Conclusions and final remarks</h2>
<ul>
<li>Currently, WCF Web API only allows asynchronous operation implementations exposing the APM model.</li>
<li>However, it is not difficult to use a <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx">Task&lt;T&gt;</a> based model with an APM interface, using the fact that <strong>Task</strong> implements <a href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx">IAsyncResult</a>.</li>
<li>While the future C# 5 asynchronous support is not available, the use of iterators and the <a href="http://code.msdn.microsoft.com/ParExtSamples">ParallelExtensionExtras</a>’s <strong>Iterate</strong> method provides for a similar experience.</li>
<li>In this post I was not concerned with measuring the scalability improvements due to the use of asynchronous operation implementation. Namely, asynchronous processing may be disadvantageous if the blocking time is very small. My main goal here was the <em>how</em> and not the <em>why</em> of using asynchronous processing.</li>
<li>The <a href="http://code.msdn.microsoft.com/ParExtSamples">ParallelExtensionExtras</a> library is full of interesting utilities, of which the <strong>Iterate</strong> and the <strong>CopyStreamToStreamAsync</strong> are just examples.</li>
</ul>
<p>Finally, feedback is greatly welcomed.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/206/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/206/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/206/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=206&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/08/05/wcf-web-api-handling-requests-asynchronously/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/08/async_thumb.png" medium="image">
			<media:title type="html">async</media:title>
		</media:content>
	</item>
		<item>
		<title>ISEL Tech Presentation</title>
		<link>http://pfelix.wordpress.com/2011/05/25/isel-tech-presentation/</link>
		<comments>http://pfelix.wordpress.com/2011/05/25/isel-tech-presentation/#comments</comments>
		<pubDate>Wed, 25 May 2011 08:03:16 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[slides]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/05/25/isel-tech-presentation/</guid>
		<description><![CDATA[My ISEL Tech 2011 WCF Web API slides are here:http://pmhsfelix.github.com/ISELTech11/ The code is available from github: https://github.com/pmhsfelix/ISELTech11 For generating the HTML 5 slides from markdown, I used the following great tool: https://github.com/atiw003/html5-slides-markdown<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=202&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My ISEL Tech 2011 WCF Web API slides are here:<a href="http://pmhsfelix.github.com/ISELTech11/">http://pmhsfelix.github.com/ISELTech11/</a></p>
<p>The code is available from github: <a href="https://github.com/pmhsfelix/ISELTech11">https://github.com/pmhsfelix/ISELTech11</a></p>
<p>For generating the HTML 5 slides from markdown, I used the following great tool: <a href="https://github.com/atiw003/html5-slides-markdown"><font color="#0066cc">https://github.com/atiw003/html5-slides-markdown</font></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/202/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=202&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/05/25/isel-tech-presentation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF Web API&#8211;Description Model</title>
		<link>http://pfelix.wordpress.com/2011/05/08/wcf-web-apidescription-model/</link>
		<comments>http://pfelix.wordpress.com/2011/05/08/wcf-web-apidescription-model/#comments</comments>
		<pubDate>Sun, 08 May 2011 21:25:22 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/05/08/wcf-web-apidescription-model/</guid>
		<description><![CDATA[This is the eighth post on a&#160;series&#160;about the new Preview 4 of WCF Web API. The previous posts were: Elementary programming model Self-hosting Self-hosting, HTTPS and HTTP Basic Authentication IIS Hosting HTTP Message Classes Processing Architecture HTTP Content Classes In this post, I shortly present the description model. Service Description For me, one of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=200&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="widows:2;text-transform:none;text-indent:0;letter-spacing:normal;border-collapse:separate;font:medium &#039;white-space:normal;orphans:2;color:rgb(0,0,0);word-spacing:0;" class="Apple-style-span"><span style="font-family:georgia, &#039;color:rgb(34,34,34);font-size:14px;" class="Apple-style-span">
<p style="line-height:25px;margin:0 0 10px;padding:0;">This is the eighth post on a<span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a><span style="margin:0;padding:0;" class="Apple-converted-space">&#160;</span>about the new Preview 4 of WCF Web API. The previous posts were:</p>
<ul style="margin:0 0 0 30px;padding:0;">
<li style="margin:0 0 10px;padding:0;"><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apielementary-programming-model/">Elementary programming model</a> </li>
<li style="margin:0 0 10px;padding:0;"><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/20/wcf-web-apiself-hosting/">Self-hosting</a> </li>
<li style="margin:0 0 10px;padding:0;"><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/21/wcf-web-api-self-hosting-https-and-http-basic-authentication/">Self-hosting, HTTPS and HTTP Basic Authentication</a> </li>
<li style="margin:0 0 10px;padding:0;"><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/22/wcf-web-apiiis-hosting/">IIS Hosting</a> </li>
<li style="margin:0 0 10px;padding:0;"><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/23/wcf-web-apihttp-message-classes/">HTTP Message Classes</a> </li>
<li style="margin:0 0 10px;padding:0;"><a style="color:rgb(0,66,118);text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">Processing Architecture</a> </li>
<li style="margin:0 0 10px;padding:0;"><a href="https://pfelix.wordpress.com/2011/05/07/http-content-classes/">HTTP Content Classes</a> </li>
</ul>
<p style="margin:0 0 10px;padding:0;">In this post, I shortly present the description model.</p>
<h3>Service Description</h3>
<p>For me, one of the key concepts required to know and use WCF is the description model – an in-memory object representation of the service.</p>
<p>The original WCF description classes, heavily based on the SOAP model, are represented in the left part of the following diagram:</p>
<ul>
<li>The model root is the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedescription.aspx">ServiceDescription</a> class:
<ul>
<li>An instance of this class is reachable via the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx">ServiceHost</a> class. </li>
<li>The <strong>ServiceDescription</strong> class includes the following properties;
<ul>
<li><strong>ServiceType</strong>, with the <strong>Type</strong> of the class that implements the service; </li>
<li><strong>Behaviors</strong>, containing the set of host-scoped behaviors; </li>
<li><strong>Endpoints</strong>, referencing all the service’s endpoints. </li>
</ul>
</li>
</ul>
</li>
<li>The next level on the description is the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.serviceendpoint.aspx">ServiceEndpoint</a>. This class represents one endpoint, namely
<ul>
<li>The <strong>Address</strong> – an <strong>EndpointAddress</strong>. </li>
<li>The <strong>Binding</strong> – a <strong>Binding</strong> derived class. </li>
<li>The <strong>Contract</strong> –a <strong>ContractDescription</strong>. </li>
</ul>
</li>
<li>Finally, the <strong>ContractDescription</strong> is composed by a set of <strong>OperationDescription</strong>, one for each of the service’s operations. </li>
</ul>
<p style="margin:0 0 10px;padding:0;"><a href="http://pfelix.files.wordpress.com/2011/05/description-2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;padding-top:0;border-width:0;" title="Description.2" border="0" alt="Description.2" src="http://pfelix.files.wordpress.com/2011/05/description-2_thumb.png?w=615&#038;h=707" width="615" height="707" /></a></p>
<p>   </span></span><br />
<h3><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> Specific Description</h3>
<p>The concepts of <em>service</em>, <em>endpoint</em>, <em>contract</em> and <em>operation </em>are still applicable to WCF Web API. However, there are new classes, showed in the right part of the above diagram, for representing the specific Web API aspects:</p>
<ul>
<li>The <strong>HttpEndpoint</strong> derives from <strong>ServiceEndpoint</strong>, and adds properties to describe concepts of the new model (e.g. message and operation handler factories). </li>
<li>The <strong>HttpBinding</strong> derives from <strong>Binding</strong>, and is used on the WCF Web API endpoints. </li>
<li>The <strong>HttpOperationDescription</strong> describes an Web API operation, namely the input parameters, the output parameters and the return value. These parameters are of type <strong>HttpParameter</strong>. </li>
</ul>
<p>These last two description classes play a fundamental role on the service configuration. For instance, on the <a href="https://pfelix.wordpress.com/2011/04/21/wcf-web-api-self-hosting-https-and-http-basic-authentication/">WCF Web API – Self-hosting, HTTPS and HTTP Basic Authentication</a> post, I present the following operation handler factory</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:ecaac641-d432-4913-acd7-630ecdbd9296" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true;">
class MyOperationHandlerFactory : HttpOperationHandlerFactory
{
    protected override Collection&lt;HttpOperationHandler&gt; OnCreateRequestHandlers(ServiceEndpoint endpoint, HttpOperationDescription operation)
    {
        var coll = base.OnCreateRequestHandlers(endpoint, operation);
        if (operation.InputParameters.Any(p =&gt; p.Type.Equals(typeof(IPrincipal))))
        {
            var binding = endpoint.Binding as HttpBinding;
            if (binding != null &amp;&amp; binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Basic)
            {
                coll.Add(new PrincipalFromBasicAuthenticationOperationHandler());
            }
        }
        return coll;
    }
}
</pre>
</pre>
</div>
<p>Notice how the <strong>OnCreateRequestHandlers</strong> method receives both the <strong>ServiceEndpoint</strong> and <strong>HttpOperationDescription</strong> classes, which describe the endpoint and operation where the created handlers are going to be added (<a href="https://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">remember</a> that there is a operation handler stack per operation). Notice also how the <strong>operation.InputParameters</strong> property is used to check if the operation has an <strong>IPrincipal</strong> parameter.</p>
<p>This example shows how the service description can be used to decide if a certain operation handler should be added or not.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/200/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=200&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/05/08/wcf-web-apidescription-model/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/05/description-2_thumb.png" medium="image">
			<media:title type="html">Description.2</media:title>
		</media:content>
	</item>
		<item>
		<title>WCF Web API &#8211; HTTP content classes</title>
		<link>http://pfelix.wordpress.com/2011/05/07/http-content-classes/</link>
		<comments>http://pfelix.wordpress.com/2011/05/07/http-content-classes/#comments</comments>
		<pubDate>Sat, 07 May 2011 13:57:49 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/2011/05/07/http-content-classes/</guid>
		<description><![CDATA[This is the seventh post on a series about the new Preview 4 of WCF Web API. The previous posts were: Elementary programming model Self-hosting Self-hosting, HTTPS and HTTP Basic Authentication IIS Hosting HTTP Message Classes Processing Architecture This post presents the HTTP content class hierarchy. The HTTP Message Classes post introduced the HttpRequestMessage and HttpResponseMessage classes, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=195&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="line-height:25px;margin:0 0 10px;padding:0;">This is the seventh post on a<span class="Apple-converted-space" style="margin:0;padding:0;"> </span><a style="color:#004276;text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apipreview-4/">series</a><span class="Apple-converted-space" style="margin:0;padding:0;"> </span>about the new Preview 4 of WCF Web API. The previous posts were:</p>
<ul style="margin:0 0 0 30px;padding:0;">
<li style="margin:0 0 10px;padding:0;"><a style="color:#004276;text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/19/wcf-web-apielementary-programming-model/">Elementary programming model</a></li>
<li style="margin:0 0 10px;padding:0;"><a style="color:#004276;text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/20/wcf-web-apiself-hosting/">Self-hosting</a></li>
<li style="margin:0 0 10px;padding:0;"><a style="color:#004276;text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/21/wcf-web-api-self-hosting-https-and-http-basic-authentication/">Self-hosting, HTTPS and HTTP Basic Authentication</a></li>
<li style="margin:0 0 10px;padding:0;"><a style="color:#004276;text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/22/wcf-web-apiiis-hosting/">IIS Hosting</a></li>
<li style="margin:0 0 10px;padding:0;"><a style="color:#004276;text-decoration:underline;margin:0;padding:0;" href="http://pfelix.wordpress.com/2011/04/23/wcf-web-apihttp-message-classes/">HTTP Message Classes</a></li>
<li style="margin:0 0 10px;padding:0;"><a href="https://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">Processing Architecture</a></li>
</ul>
<p style="margin:0 0 10px;padding:0;">This post presents the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> content class hierarchy.</p>
<p style="margin:0 0 10px;padding:0;">The <a href="https://pfelix.wordpress.com/2011/04/23/wcf-web-apihttp-message-classes/">HTTP Message Classes</a> post introduced the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpRequestMessage.cs">HttpRequestMessage</a> and <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a> classes, which represent HTTP requests and responses. Both this classes have a <strong>Content</strong> property, of type <strong>HttpContent</strong>, that represents the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3">HTTP message body</a>.</p>
<p style="margin:0 0 10px;padding:0;">The <strong>HttpContent</strong> abstract class is just the root of a class hierarchy with multiple content classes, as presented in the following class diagram.</p>
<p style="margin:0 0 10px;padding:0;"><a href="http://pfelix.files.wordpress.com/2011/05/httpcontent-annot_.png"><img style="background-image:none;padding-left:0;padding-right:0;display:block;float:none;padding-top:0;border:0;" title="HttpContent.annot" src="http://pfelix.files.wordpress.com/2011/05/httpcontent-annot_thumb.png?w=647&#038;h=826" alt="HttpContent.annot" width="647" height="826" border="0" /></a></p>
<p>I’ve divided this class diagram into several regions, in order to highlight the different design aspects:</p>
<ul>
<li>The <strong>HttpContent</strong> is the hierarchy root, and is referenced by both the <strong>HttpRequestMessage</strong> and <strong>HttpResponseMessage</strong>  classes.</li>
<li>There are several concrete <strong>HttpContent</strong>-derived classes for handling basic content types.</li>
<ul>
<li>The <strong>StreamContent</strong>, <strong>ByteArrayContent</strong> and <strong>StringContent</strong> classes are self-explanatory.</li>
<li>The <strong>FormUrlEncoded</strong> is used to create <strong>application/x-www-form-urlencoded</strong> type content, based on a <strong>Iterable&lt;KeyValuePair&lt;string,string&gt;&gt;</strong> containing (name,value) pairs.</li>
</ul>
<li>The <strong>ObjectContent</strong> class represents object-based content, i. e.</li>
<ul>
<li>content produced by the serialization/formatting of an object;</li>
<li>content that is to be read as an object, using deserialization/unformatting.</li>
</ul>
<li>The <strong>ObjectContent&lt;T&gt;</strong> generic class provides a more typed version of <strong>ObjectContent</strong>: instead of dealing with plain <strong>object</strong>, this classes provides methods to obtain a <strong>T</strong> from the content or to construct a content based on a <strong>T</strong>.</li>
<li>This <strong>ObjectContent&lt;T&gt;</strong> is used by both the new <strong>HttpRequestMessage&lt;T&gt;</strong> and <strong>HttpResponseMessage&lt;T&gt;</strong> classes. This two classes represent HTTP request and responses, similarly to the non-generic <strong>HttpResponseMessage</strong> and <strong>HttpRequestMessage</strong> classes, with one big difference: the content is strongly-typed &#8211; a <strong>T </strong>instance.</li>
<li>The conversion between byte streams and object instances is the responsibility of media-type formatters, represented by the <strong>MediaTypeFormatter</strong> abstract base class. This class contains two abstract methods, <strong>OnReadFromStream</strong> and <strong>OnWriteToStream,</strong> implemented by concrete classes such as <strong>XmlMediaTypeFormatter</strong> or <strong>JsonMediaTypeFormatter</strong>.</li>
</ul>
<h3>Concluding notes</h3>
<ul>
<li>This post was based on the observation of the Preview 4 source code, available at <a href="http://www.codeplex.com">http://www.codeplex.com</a>. Since this is just a preview, this model is to be interpreted as “work in progress”.</li>
<li>On future post, I will show how both the content classes and the generic request and response classes can be used as operation parameters.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pfelix.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pfelix.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pfelix.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pfelix.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pfelix.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pfelix.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pfelix.wordpress.com/195/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&amp;blog=3662583&amp;post=195&amp;subd=pfelix&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2011/05/07/http-content-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2011/05/httpcontent-annot_thumb.png" medium="image">
			<media:title type="html">HttpContent.annot</media:title>
		</media:content>
	</item>
	</channel>
</rss>
