<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Pedro Félix's shared memory</title>
	
	<link>http://pfelix.wordpress.com</link>
	<description>Conjectures on software</description>
	<lastBuildDate>Wed, 08 May 2013 21:18:55 +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's shared memory" />
	
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/pfelix" /><feedburner:info uri="pfelix" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pfelix.wordpress.com/?pushpress=hub" /><item>
		<title>Using HttpClient with SSL/TLS-based client side authentication</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/cYIOwYc9tYk/</link>
		<comments>http://pfelix.wordpress.com/2012/12/16/using-httpclient-with-ssltls/#comments</comments>
		<pubDate>Sun, 16 Dec 2012 23:18:15 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://pfelix.wordpress.com/?p=343</guid>
		<description><![CDATA[The HttpClient is a the new class for making HTTP requests and receiving the associated HTTP responses, introduced in the 4.5 version of .NET. In a previous post  - The new .NET HttpClient class - we described its the core concepts and architecture. One of the main takeaways was the concept of client handler, which is just a message [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=343&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <strong><a title="HttpClient" href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx">HttpClient</a></strong> is a the new class for making HTTP requests and receiving the associated HTTP responses, introduced in the 4.5 version of .NET. In a previous post  - <a href="https://pfelix.wordpress.com/2012/01/11/the-new-net-httpclient-class/">The new .NET HttpClient class</a> - we described its the core concepts and architecture. One of the main takeaways was the concept of <em>client handler</em>, which is just a <a href="http://pfelix.wordpress.com/2011/04/26/wcf-web-apiprocessing-architecture/">message handler</a> responsible for delivering the HTTP messages to the network stack and receiving the responses from it. Typically, the client handler will be at the end of the message handler pipeline used by the client.</p>
<p>The current&#8217;s post goal is to describe how to configure this new HTTP client class with client-side authentication based on the TLS (<em>Transport Layer Security</em>) protocol.</p>
<p>The <strong>HttpClient</strong> class does not contain any configuration properties or methods related to TLS. This is because the <strong>HttpClient</strong> class is independent of the used HTTP message transport mechanism. Namely, it is even possible to connect a <strong>HttpClient</strong> directly to an <strong>HttpServer</strong> instance, without any network intervention, as described in another <a href="http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/">post</a>.</p>
<p>Instead, the TLS configuration requires dealing directly with one of the available client handlers presented in the previous post : <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.aspx"><strong>HttpClientHandler</strong> </a>and <a href="http://msdn.microsoft.com/en-us/library/system.net.http.webrequesthandler.aspx"><strong>WebRequestHandler</strong></a>.</p>
<p>The first option is to explicitly configure the <strong>HttpClient</strong> with a <strong>HttpClientHandler</strong> instance, containing its <strong>ClientCertificateOptions</strong> property set to <strong>Automatic.</strong></p>
<p>The resulting <strong>HttpClient</strong> can then be used normally: if during a connection handshake the server requires the client certificate, the <strong>HttpClientHandler</strong> instance will automatically select a compatible client certificate for the user&#8217;s personal certificate store.</p>
<pre class="brush: csharp; title: ; notranslate">
var client = new HttpClient(

 new HttpClientHandler{
   ClientCertificateOptions = ClientCertificateOption.Automatic
 });
// ...
</pre>
<p>This option is the only one available for <em>Windows Store</em> applications.</p>
<p>For <em>classical</em> scenarios (e.g. console, WinForms or WPF applications) there is a second option using the <strong>WebRequestHandler</strong>, which provides more control over the configuration.</p>
<pre class="brush: csharp; title: ; notranslate">
var clientHandler = new WebRequestHandler()
clientHandler.ClientCertificates.Add(cert);
var client = new HttpClient(clientHandler)
</pre>
<p>where <strong>cert</strong> is a <strong>X509Certificate2</strong> instance representing the client certificate.<br />
This instance can be constructed directly from a PFX file or obtained from a Windows certificate store</p>
<pre class="brush: csharp; title: ; notranslate">
X509Store store = null;
try
{
  store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
  store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
  // select the certificate from store.Certificates ...
}
finally
{
  if(store != null) store.Close();
}
</pre>
<p>And that&#8217;s it. Hope it helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/343/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/343/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=343&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/cYIOwYc9tYk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/12/16/using-httpclient-with-ssltls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/12/16/using-httpclient-with-ssltls/</feedburner:origLink></item>
		<item>
		<title>Slides for the “OAuth 2.0: Theory and Practice” session</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/TdI8LE9PWjA/</link>
		<comments>http://pfelix.wordpress.com/2012/11/27/slides-for-the-oauth-2-0-theory-and-practice-session/#comments</comments>
		<pubDate>Tue, 27 Nov 2012 17:03:36 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://pfelix.wordpress.com/?p=341</guid>
		<description><![CDATA[The slides of the &#8220;OAuth 2.0: Theory and Practice&#8221; Codebits 2012 session, that I co-authored with Daniel Correia, are available here.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=341&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The slides of the <a href="https://codebits.eu/intra/s/session/269">&#8220;OAuth 2.0: Theory and Practice&#8221; Codebits 2012</a> session, that I co-authored with <a href="https://twitter.com/AriOps">Daniel Correia</a>, are available <a href="http://pfelix.files.wordpress.com/2012/11/codebits12-oauth2-slides.pdf">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/341/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/341/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=341&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/TdI8LE9PWjA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/11/27/slides-for-the-oauth-2-0-theory-and-practice-session/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/11/27/slides-for-the-oauth-2-0-theory-and-practice-session/</feedburner:origLink></item>
		<item>
		<title>JSON Web Tokens and the new JWTSecurityTokenHandler class</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/7nOADPQzo4E/</link>
		<comments>http://pfelix.wordpress.com/2012/11/27/json-web-tokens-and-the-new-jwtsecuritytokenhandler-class/#comments</comments>
		<pubDate>Tue, 27 Nov 2012 00:30:59 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[claims]]></category>
		<category><![CDATA[JWT]]></category>
		<category><![CDATA[WIF]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=334</guid>
		<description><![CDATA[Last week, Vittorio Bertocci announced the developer preview of the new JWT Security Token Handler, which provides support for a important piece of the modern identity and access control management puzzle. What are security tokens? In the context of the claims model, a security token is an interoperable  container of security-related information, typically identity claims, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=334&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Last week, <a href="http://blogs.msdn.com/b/vbertocci/">Vittorio Bertocci</a> announced the <a href="https://nuget.org/packages/Microsoft.IdentityModel.Tokens.JWT">developer preview</a> of the new JWT Security Token Handler, which provides support for a important piece of the modern identity and access control management puzzle.</p>
<h2>What are security tokens?</h2>
<p>In the context of the <a href="https://pfelix.wordpress.com/2010/06/30/alice-in-claims-the-claims-model/">claims model</a>, a <em>security token</em> is an interoperable  container of security-related information, typically identity claims, securely packaged for communication between two or more parties. This packaging ensures properties such as:</p>
<ul>
<li>Confidentiality – only the authorized receiver should be able to access the contained information</li>
<li>Integrity – the authorized receiver should be able to detect any modifications to token, while in transit between the two parties.</li>
</ul>
<p>On Web Single-Sign On protocols, security tokens are used to securely transport the identity information from the identity provider to the identity consumer. On a delegated authorization protocol, such as OAuth 2.0, security tokens can be used to convey the authorization information from the client to the resource server.</p>
<p>For instance, the SAML (Security Assertion Markup Language) assertion is an example of a very popular token format, used by  Single-Sign On protocols such as: <a href="http://shibboleth.net/">Shibboleth</a>, the <a href="http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf">SAML protocols</a> and <a href="http://msdn.microsoft.com/en-us/library/bb498017.aspx">WS-Federation</a>. SAML assertions are XML-based and use the <a href="http://www.w3.org/TR/xmldsig-core/">XML Digital Signature</a> and <a href="http://www.w3.org/TR/xmlenc-core/">XML Encryption</a> standards for providing integrity and confidentiality.</p>
<h2>What is JWT?</h2>
<p>JWT stands for  <a href="http://datatracker.ietf.org/doc/draft-ietf-oauth-json-web-token">JSON Web Token</a>, and is a new format for packing and protecting security information. It is based on the <a href="http://www.json.org/">JSON</a> (JavaScript Object Notation) syntax and aims to be usable in <a href="http://datatracker.ietf.org/doc/draft-ietf-oauth-json-web-token">“space constrained environments such as HTTP Authorization headers and URI query parameters”</a>.</p>
<p>The following example (taken from the <a href="http://datatracker.ietf.org/doc/draft-ietf-oauth-json-web-token">spec</a>), represents a unprotected token (line breaks added for display purposes)</p>
<pre><strong>eyJhbGciOiJub25lIn0</strong>
<strong>.</strong>
<strong>eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ</strong></pre>
<p>&nbsp;</p>
<p>The encoded token is composed by a sequence of parts, separated by the ‘.’ character. Each part is the <a href="http://tools.ietf.org/html/rfc4648">base64url</a> encoding of an octet stream. In this example, both octet stream result from the UTF-8 encoding of JSON objects. The first object (encoded in the first part) is the <em>JWT header</em></p>
<p><strong>{&#8220;alg&#8221;:&#8221;none&#8221;}</strong></p>
<p>The header defines the token cryptographic protection, which is ‘none’ in this case.</p>
<p>The second object (encoded in the second part) is the <em>JWT Claims Set</em></p>
<p><strong>{&#8220;iss&#8221;:&#8221;joe&#8221;,</p>
<p>&#8220;exp&#8221;:1300819380, </strong></p>
<p>&#8220;<a href="http://example.com/is_root&quot;:true"><strong>http://example.com/is_root&#8221;:true</strong></a><strong>}</strong></p>
<p>The JWT Claims Set object is a container of claims, where the object’s property corresponds to the claim type and the property’s value contains the claims value. Some claims types are defined by the JWT spec (e.g. “iss” and “exp”), while others are context specific (e.g. “http://example.com/is_root”).</p>
<p>We will see more examples of JWT tokens after presenting the JWT Security Token Handler.</p>
<h2>What are Security Token Handlers?</h2>
<p><em>Security Token Handlers</em> are a concept introduced by the  WIF (<a href="http://msdn.microsoft.com/en-us/library/hh377151.aspx">Windows Identity Foundation</a>) framework, which is now an integral part of the .NET 4.5 framework. A token handler has multiple responsibilities, namely:</p>
<ul>
<li>Serialize and deserialize tokens between a XML or string format and a <a href="http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytoken.aspx">SecurityToken</a>-derived instance;</li>
<li>Validate security tokens and extract the contained claims into a claims identity or a claims principal;</li>
<li>Create a token from a token description.</li>
</ul>
<p>This behavior is defined by the abstract <a href="http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx">SecurityTokenHandler</a> class, with multiple concrete derived classes for each token type (e.g. the <a href="http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.saml2securitytokenhandler.aspx">Saml2SecurityTokenHandler</a> class).</p>
<h2>The JTWSecurityTokenHandler class</h2>
<p>The recently announced <a href="https://nuget.org/packages/Microsoft.IdentityModel.Tokens.JWT"><strong>Microsoft.IdentityModel.Tokens.JWT</strong></a> NuGet package contains a new token handler for the JWT token format – the <strong>JWTSecurityTokenHandler</strong> class – depicted in the next diagram.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/11/tokenhandlers.png"><img style="background-image:none;float:none;padding-top:0;padding-left:0;margin-left:auto;display:block;padding-right:0;margin-right:auto;border-width:0;" title="TokenHandlers" alt="TokenHandlers" src="http://pfelix.files.wordpress.com/2012/11/tokenhandlers_thumb.png?w=581&#038;h=480" height="480" width="581" /></a></p>
<p>As a token handler,  the <strong>JWTSecurityTokenHandler</strong> can be used to create and validate JWT tokens, as shown by the next example</p>
<p>&nbsp;</p>
<script src="https://gist.github.com/4151369.js"></script>
<p>&nbsp;</p>
<ul>
<li>First, we create a token handler and a symmetric key, that will be used by both the sending and the receiving party to sign and validate the token, respectively.</li>
<li>Then, we create a token descriptor, defining the token contents, namely:
<ul>
<li>The contained claims, i.e., the subject of the token,</li>
<li>The token issuer name,</li>
<li>The intended recipient of the token (AppliesToAddress),</li>
<li>The token lifetime, defined by a not before and an expires date-time,</li>
</ul>
</li>
<li>The token descriptor also contains the signing credentials, namely the symmetric key and the MAC (Message Authentication Code) algorithm identifier (“<span style="white-space:pre;text-transform:none;word-spacing:0;float:none;color:#dd1144;text-align:left;"><a href="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256">http://www.w3.org/2001/04/xmldsig-more#hmac-sha256</a></span>”).</li>
<li>Then, we use the token handler to create the token from the token descriptor. We also use the token handler to serialize the token into a string.</li>
<li>On the receiving side, we begin by defining the validation parameters, namely:
<ul>
<li>The allowed audience, i.e., the value defined in the AppliestoAddress property of the token descriptor. This value should be an identifier of the receiving party.</li>
<li>The validation cryptographic, in the form of a BinarySecretSecurityToken containing the shared symmetric key.</li>
<li>The name of the accepted issuer.</li>
</ul>
</li>
<li>Finally, we use the token handler to simultaneously deserialize the token, validate its signature and extract the contained claims into a claims principal.</li>
<li>We end the example by asserting that the claims principal does contains the Name and Role claims inserted in the token by the issuer.</li>
</ul>
<p>&nbsp;</p>
<p>The serialized token is just the concatenation of three base64url encoded parts (line breaks added for display purposes).</p>
<p>&nbsp;</p>
<p><strong>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9</strong></p>
<p><strong>.</strong></p>
<p><strong>eyJhdWQiOiJodHRwOi8vd3d3LmV4YW1wbGUuY29tIiwiaXNzIjoic2VsZiIsIm5iZiI6MTM1Mzk3NDczNiwi</strong></p>
<p><strong>ZXhwIjoxMzUzOTc0ODU2LCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5</strong></p>
<p><strong>L2NsYWltcy9uYW1lIjoiUGVkcm8iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYv</strong></p>
<p><strong>aWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBdXRob3IifQ</strong></p>
<p><strong>.</strong></p>
<p><strong>a-Tu5ojQSyiGSzTb9E5QbEYxyhomywzh2wqKs4El7lc</strong></p>
<p>&nbsp;</p>
<p>The first part contains the JWT Header</p>
<p><strong>{&#8220;typ&#8221;:&#8221;JWT&#8221;,&#8221;alg&#8221;:&#8221;HS256&#8243;}</strong></p>
<p>The second part contains the claims, including the audience, issuer and validity</p>
<p><strong>{&#8220;aud&#8221;:&#8221;</strong><a href="http://www.example.com&quot;,"><strong>http://www.example.com&#8221;,</strong></a></p>
<p><strong>&#8220;iss&#8221;:&#8221;self&#8221;,&#8221;nbf&#8221;:1353973142,&#8221;exp&#8221;:1353973262,</strong></p>
<p>&#8220;<strong><a href="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" rel="nofollow">http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name</a></strong><strong>&#8220;:&#8221;Pedro&#8221;,</strong></p>
<p><strong>&#8220;<a href="http://schemas.microsoft.com/ws/2008/06/identity/claims/role&#038;#8221" rel="nofollow">http://schemas.microsoft.com/ws/2008/06/identity/claims/role&#038;#8221</a>;:&#8221;Author&#8221;}</strong></p>
<p>Finally, the third part is the signature value, computed by the MAC algorithm over the first two parts.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/334/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/334/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=334&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/7nOADPQzo4E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/11/27/json-web-tokens-and-the-new-jwtsecuritytokenhandler-class/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/11/tokenhandlers_thumb.png" medium="image">
			<media:title type="html">TokenHandlers</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/11/27/json-web-tokens-and-the-new-jwtsecuritytokenhandler-class/</feedburner:origLink></item>
		<item>
		<title>ASP.NET Web API: Creating an Host using Azure Service Bus</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/SJKmT4uMsrw/</link>
		<comments>http://pfelix.wordpress.com/2012/03/15/asp-net-web-api-creating-an-host-using-azure-service-bus/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 23:53:50 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=324</guid>
		<description><![CDATA[In the last posts, I’ve presented the new ASP.NET Web API&#160;processing architecture and described three different hosting capabilities, supported “out of the box”: web hosting, in-memory hosting and self-hosting. In this post, I will describe the development of a custom host using the Azure Service Bus&#160;relaying capabilities. This new host enables the exposure of a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=324&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In the last posts, I’ve presented the new <a href="http://www.asp.net/web-api">ASP.NET Web API</a>&#160;<a href="https://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/">processing architecture</a> and described three different hosting capabilities, supported “out of the box”: <a href="https://pfelix.wordpress.com/2012/03/07/asp-net-web-api-web-hosting/">web hosting</a>, <a href="https://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/">in-memory hosting</a> and <a href="https://pfelix.wordpress.com/2012/03/08/asp-net-web-api-self-hosting/">self-hosting</a>.</p>
<p>In this post, I will describe the development of a custom host using the <a href="https://www.windowsazure.com/en-us/home/features/service-bus/">Azure Service Bus</a>&#160;<a href="https://www.windowsazure.com/en-us/develop/net/how-to-guides/service-bus-relay/">relaying capabilities</a>. This new host enables the exposure of a Web API on the public cloud, while running on a private machine (e.g. my laptop), that is, a machine without inbound connectivity (e.g. private addresses, firewall, NAT).</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/servicebusrelay.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="ServiceBusRelay" border="0" alt="ServiceBusRelay" src="http://pfelix.files.wordpress.com/2012/03/servicebusrelay_thumb.png?w=545&#038;h=160" width="545" height="160" /></a></p>
<p>This host design is inspired in the self-host architecture, namely the usage of WCF and its <a href="http://servicebus.codeplex.com/">integration</a> with the service bus and WCF. Is composed by the following main components, shown in the following diagram.</p>
<p>&#160;</p>
<p>&#160;</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/servicebushosting.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="ServiceBusHosting" border="0" alt="ServiceBusHosting" src="http://pfelix.files.wordpress.com/2012/03/servicebushosting_thumb.png?w=631&#038;h=378" width="631" height="378" /></a></p>
<p>&#160;</p>
<ul>
<li>The <strong>HttpServiceBusConfiguration</strong> class derives from <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpconfiguration(v=vs.108).aspx">HttpConfiguration</a> and adds a couple of properties specific to the this scenario, such as the bus authentication credentials (<strong>IssuerName</strong> and <strong>IssuerSecret</strong>).</li>
<li>The <strong>HttpServiceBusServer</strong> is initialized with a <strong>HttpServiceBusConfiguration</strong> and internally performs the following:</li>
<ul>
<li>Creates an inner <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> instance, using the given configuration.</li>
<li>Creates a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webservicehost.aspx">WebServiceHost</a>, using the generic <strong>DispatcherService</strong> as the service class.</li>
<li>Adds an endpoint with the <a href="http://msdn.microsoft.com/en-us/library/microsoft.servicebus.webhttprelaybinding.aspx">WebHttpRelayBinding</a> binding and a <a href="http://msdn.microsoft.com/en-us/library/microsoft.servicebus.transportclientendpointbehavior.aspx">TransportClientEndpointBehavior</a>, which configures this endpoint with the credentials required when <em>listening</em> on the bus.</li>
</ul>
<li>When a request message is received, the WCF runtime delivers it to the <strong>DispatcherService</strong>, containing generic asynchronous operations to handle GET requests (<strong>BeginGet</strong> and <strong>EndGet</strong> methods) and other <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> methods (<strong>BeginInvoke</strong> and <strong>EndInvoke</strong>).</li>
</ul>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:145b68ea-6ac7-42e4-a19f-6326c5962e05" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; title: ; notranslate">
    [ServiceContract]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    internal class DispatcherService
    {
        private readonly HttpServer _server;
        private readonly HttpServiceBusConfiguration _config;

        public DispatcherService(HttpServer server, HttpServiceBusConfiguration config)
        {
            _server = server;
            _config = config;
        }

        [WebGet(UriTemplate = "*")]
        [OperationContract(AsyncPattern = true)]
        public IAsyncResult BeginGet(AsyncCallback callback, object state)
        {
            var context = WebOperationContext.Current;
            return DispatchToHttpServer(context.IncomingRequest, null, 
				context.OutgoingResponse, _config.BufferRequestContent, callback, state);
        }

        public Message EndGet(IAsyncResult ar)
        {
            var t = ar as Task;
            var stream = t.Result;
            return StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream());
        }

        [WebInvoke(UriTemplate = "*", Method = "*")]
        [OperationContract(AsyncPattern = true)]
        public IAsyncResult BeginInvoke(Stream s, AsyncCallback callback, object state)
        {
            var context = WebOperationContext.Current;
            return DispatchToHttpServer(context.IncomingRequest, s, 
				context.OutgoingResponse, _config.BufferRequestContent, callback, state);
        }

        public Message EndInvoke(IAsyncResult ar)
        {
            var t = ar as Task;
            var stream = t.Result;
            return StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream());
        }
		...
    }
</pre>
</div>
<p>&#160;</p>
<ul>
<li>These generic operations convert the WCF requests, represented by the older <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.incomingwebrequestcontext.aspx">IncomingWebRequestContext</a> class, into instances of the new <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> class. Then, they pushe these messages into the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> pipeline. When the server finally returns the responses’ <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a> instances, the generic operations convert them back into WCF messages.</li>
</ul>
<p>The code, still in alpha/”works in my machine” status, is available from <a href="https://github.com/pmhsfelix/WebApi.Explorations.ServiceBusRelayHost"><font color="#0066cc"><a href="https://github.com/pmhsfelix/WebApi.Explorations.ServiceBusRelayHost.">https://github.com/pmhsfelix/WebApi.Explorations.ServiceBusRelayHost</a></font>.</a></p>
<p>Feedback is appreciated.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/324/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=324&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/SJKmT4uMsrw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/03/15/asp-net-web-api-creating-an-host-using-azure-service-bus/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/servicebusrelay_thumb.png" medium="image">
			<media:title type="html">ServiceBusRelay</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/servicebushosting_thumb.png" medium="image">
			<media:title type="html">ServiceBusHosting</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/03/15/asp-net-web-api-creating-an-host-using-azure-service-bus/</feedburner:origLink></item>
		<item>
		<title>ASP.NET Web API: self-hosting</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/8G0B5oIDj5c/</link>
		<comments>http://pfelix.wordpress.com/2012/03/08/asp-net-web-api-self-hosting/#comments</comments>
		<pubDate>Thu, 08 Mar 2012 12:32:11 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=318</guid>
		<description><![CDATA[In the last posts, I’ve been exploring the new ASP.NET Web API Beta architecture. I started by the high-level processing architecture, then described web hosting and in-memory hosting, i.e., directly connecting a client to the server without going through the network. This post describes a third “out of the box” hosting option: self-hosting. The following [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=318&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In the last posts, I’ve been exploring the new <a href="http://www.asp.net/web-api">ASP.NET Web API</a> Beta architecture. I started by the high-level <a href="https://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/">processing architecture</a>, then described <a href="https://pfelix.wordpress.com/2012/03/07/asp-net-web-api-web-hosting/">web hosting</a> and <a href="https://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/">in-memory hosting</a>, i.e., directly connecting a client to the server without going through the network.</p>
<p>This post describes a third “out of the box” hosting option: self-hosting. The following code excerpt exemplifies the usage of the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostserver(v=vs.108).aspx">HttpSelfHostServer</a> class to host a server on a console application.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:75222b99-a132-4070-96fb-3cf907939e1c" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
    var config = new HttpSelfHostConfiguration("http://localhost:8080");
    config.Routes.MapHttpRoute("default", "{controller}/{id}", 
                                    new { id = RouteParameter.Optional });
    var server = new HttpSelfHostServer(config);
    server.OpenAsync().Wait();
    Console.WriteLine("Server is opened");
</pre>
</div>
<p>&#160;</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostserver(v=vs.108).aspx">HttpSelfHostServer</a> class derives from <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> and and is configured by a <a href="http://msdn.microsoft.com/en-us/library/hh835774(v=vs.108).aspx">HttpSelfHostConfiguration</a> instance, as shown in the following diagram.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/selfhosting.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="SelfHosting" border="0" alt="SelfHosting" src="http://pfelix.files.wordpress.com/2012/03/selfhosting_thumb.png?w=501&#038;h=203" width="501" height="203" /></a></p>
<p>&#160;</p>
<p>Internally, the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostserver(v=vs.108).aspx">HttpSelfHostServer</a> uses a WCF channel stack layer to obtain messages from the transport medium and then pushes them into the upper message handler pipeline.</p>
<p>The following section briefly presents the WCF high-level architecture, setting the ground for the description of Web API self-hosting characteristics.</p>
<h4>WCF architecture</h4>
<p>The WCF architecture is divided into two layers: the <em>channel stack layer</em> and the <em>service model layer</em>, as depicted in the following diagram.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/wcfarchitecture.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="WcfArchitecture" border="0" alt="WcfArchitecture" src="http://pfelix.files.wordpress.com/2012/03/wcfarchitecture_thumb.png?w=350&#038;h=393" width="350" height="393" /></a></p>
<p>The lower <em>channel stack layer</em> is composed by a stack of <em>channels</em> and behaves similarly to a classical network protocol stack.&#160; The channels are divided into two types: transport channels and protocol channels. Transport channels are responsible by the interface with the transport medium (e.g. TCP, MSMQ, HTTP) (<a href="http://codebetter.com/glennblock/2012/01/19/http-is-not-a-transport-protocol-http-is-not-rpc/">yes, I know, HTTP is not a transport protocol</a>), namely by receiving and sending <em>messages</em>. Protocol channels process the messages that flow up and down through the stack. A typical use case for a protocol channel is the addition of digital signatures at the sending side and the verification of those signatures at the receiving side. The transport channels use encoders to convert between the transport medium byte streams and message instances.</p>
<p>The upper <em>service model layer</em> performs the interface between the messages and methods calls, dealing with tasks such as:</p>
<ul>
<li>transforming a received message into a parameter sequence;</li>
<li>obtaining the service instance to use;</li>
<li>selecting the method to call;</li>
<li>obtaining the thread where to call the method.</li>
</ul>
<p>However, the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostserver(v=vs.108).aspx">HttpSelfHostServer</a> doesn’t use the service model layer. Instead, it directly consumes the messages retrieved from channel stack layer.</p>
<p>The concrete channel stack layer organization is <em>described</em> by bindings, as presented in the following diagram.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/wcfbindingelementschannels.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="WcfBindingElementsChannels" border="0" alt="WcfBindingElementsChannels" src="http://pfelix.files.wordpress.com/2012/03/wcfbindingelementschannels_thumb.png?w=474&#038;h=172" width="474" height="172" /></a></p>
<p>A binding is a ordered collection of binding elements, where each element roughly describes one channel or encoder. The first binding element describes the upper channel and the last element describes the lower channel, which is always a transport channel.</p>
<p>&#160;</p>
<h4>The HttpSelfHostServer and HttpSelfHostConfiguration classes</h4>
<p>Internally, the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostserver.openasync(v=vs.108).aspx">HttpSelfHostserver.OpenAsync</a> method creates and configures a <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.channels.httpbinding(v=vs.108).aspx">HttpBinding</a> instance, based on the <a href="http://msdn.microsoft.com/en-us/library/hh835774(v=vs.108).aspx">HttpSelfHostConfiguration</a> instance properties. Then it uses this binding to asynchronously create a WCF channel stack. It also creates a <em>pump</em> that pulls messages from this channel stack, converts them into <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> instances and pushes these new requests into the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a>, that is, the message handler pipeline.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/selfhostingdiagram.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="SelfHostingDiagram" border="0" alt="SelfHostingDiagram" src="http://pfelix.files.wordpress.com/2012/03/selfhostingdiagram_thumb.png?w=470&#038;h=561" width="470" height="561" /></a></p>
<p>When self-hosting, most of the WCF HTTP binding capabilities and settings are available. The configuration of the internally created <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.channels.httpbinding(v=vs.108).aspx">HttpBinding</a> instance can be accomplished in two ways. The first is to use <a href="http://msdn.microsoft.com/en-us/library/hh835774(v=vs.108).aspx">HttpSelfHostConfiguration</a> properties, such as <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostconfiguration.maxbuffersize(v=vs.108).aspx">MaxBufferSize</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostconfiguration.transfermode(v=vs.108).aspx">TransferMode</a>, that will be used to configure the internal <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostconfiguration.transfermode(v=vs.108).aspx">HttpBinding</a> instance. The second is to create a <a href="http://msdn.microsoft.com/en-us/library/hh835774(v=vs.108).aspx">HttpSelfHostConfiguration</a> derived class and override the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.selfhost.httpselfhostconfiguration.onconfigurebinding(v=vs.108).aspx">OnConfigureBinding</a> method, which receives the internally created binding instance. This method has the opportunity to change the binding settings before it is used to create the channel stack.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/selfhostingdetail.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="SelfHostingDetail" border="0" alt="SelfHostingDetail" src="http://pfelix.files.wordpress.com/2012/03/selfhostingdetail_thumb.png?w=482&#038;h=505" width="482" height="505" /></a></p>
<p>In a future post, I will show how to create a custom host. Until then, comments are welcomed.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/318/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=318&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/8G0B5oIDj5c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/03/08/asp-net-web-api-self-hosting/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/selfhosting_thumb.png" medium="image">
			<media:title type="html">SelfHosting</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/wcfarchitecture_thumb.png" medium="image">
			<media:title type="html">WcfArchitecture</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/wcfbindingelementschannels_thumb.png" medium="image">
			<media:title type="html">WcfBindingElementsChannels</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/selfhostingdiagram_thumb.png" medium="image">
			<media:title type="html">SelfHostingDiagram</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/selfhostingdetail_thumb.png" medium="image">
			<media:title type="html">SelfHostingDetail</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/03/08/asp-net-web-api-self-hosting/</feedburner:origLink></item>
		<item>
		<title>ASP.NET Web API: web hosting</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/vyGfv_bGXIM/</link>
		<comments>http://pfelix.wordpress.com/2012/03/07/asp-net-web-api-web-hosting/#comments</comments>
		<pubDate>Wed, 07 Mar 2012 12:58:24 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=306</guid>
		<description><![CDATA[In a previous post, I described the processing architecture of the new ASP.NET Web API, namely its division into three layers: hosting, message handler pipeline and controller handling. In this post, I’m going to address one of the hosting options: web hosting, i.e., hosting on top of the ASP.NET classical pipeline. Routing On the ASP.NET [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=306&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In a <a href="https://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/">previous post</a>, I described the processing architecture of the new <a href="http://www.asp.net/web-api">ASP.NET Web API</a>, namely its division into three layers: hosting, message handler pipeline and controller handling.</p>
<p>In this post, I’m going to address one of the hosting options: <em>web hosting</em>, i.e., hosting on top of the ASP.NET classical pipeline.</p>
<h4>Routing</h4>
<p>On the ASP.NET platform, routing is commonly performed by adding routes to the <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routetable.routes.aspx">RouteTable.Routes</a> static property, which holds a <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.aspx">RouteCollection</a>. For example, the following code excerpt shows the default routing defined by the ASP.NET MVC project template.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:647731bd-2177-46b7-96fb-737ca8272f52" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
        );
    }
</pre>
</div>
<p>Most of the routing logic is performed by the <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.urlroutingmodule.aspx">UrlRoutingModule</a>, attached to the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.postresolverequestcache.aspx">PostResolveRequestCache</a> ASP.NET pipeline event. On each request, this module matches the current request against the route collection, obtaining a <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routedata.aspx">RouteData</a> instance. If there is a match, then:</p>
<ol>
<li>A route handler is obtained from the route data. </li>
<li>A HTTP handler, implementing the <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx">IHttpHandler</a> interface, is obtained from the route handler. </li>
<li>Finally, the current request context is mapped to the above HTTP handler.<br />
    <br />As a consequence, at the end of the ASP.NET pipeline the request is sent to this handler . </li>
</ol>
<h4>Web API integration</h4>
<p>When hosting on ASP.NET, the Web API specific configuration is defined on a singleton <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpconfiguration(v=vs.108).aspx">HttpConfiguration</a> object, accessible via the static <a href="http://msdn.microsoft.com/en-us/library/system.web.http.globalconfiguration.configuration(v=vs.108).aspx">GlobalConfiguration.Configuration</a> property. </p>
<p>Web API also defines a couple of new <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.aspx">RouteCollection</a> extension methods, named <a href="http://msdn.microsoft.com/en-us/library/hh835153(v=vs.108).aspx">MapHttpRoute</a>, to register Web API specific routes. The following code excerpt contains an example configuration.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:9f6fe60f-c638-4df9-8ae3-035e3dfbab01" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; title: ; notranslate">
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Routes.MapHttpRoute("default", "{controller}/{id}",  new {id = UrlParameter.Optional});
    // other configuration settings
</pre>
</div>
<p>&#160;</p>
<p>Notice:</p>
<ul>
<li>The static <a href="http://msdn.microsoft.com/en-us/library/system.web.http.globalconfiguration.configuration(v=vs.108).aspx">GlobalConfiguration.Configuration</a> property, used to obtain the <strong>config</strong> reference. Internally, this configuration object points to the global <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routetable.routes.aspx">RouteTable.Routes</a> route collection. </li>
<li>The usage of the <a href="http://msdn.microsoft.com/en-us/library/hh835153(v=vs.108).aspx">MapHttpRoute</a> extension method, when adding the route. </li>
</ul>
<p>The routes added to the route collection by the <a href="http://msdn.microsoft.com/en-us/library/hh835153(v=vs.108).aspx">MapHttpRoute</a> extension methods use the new <a href="http://msdn.microsoft.com/en-us/library/system.web.http.webhost.httpcontrollerroutehandler(v=vs.108).aspx">HttpControllerRouteHandler</a> route handler . When a route added via <a href="http://msdn.microsoft.com/en-us/library/hh835153(v=vs.108).aspx">MapHttpRoute</a> is matched by a request, the associated route handler returns a new type of handler - the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.webhost.httpcontrollerhandler(v=vs.108).aspx">HttpControllerHandler</a> - which implements the asynchronous <strong>IAsyncHttpHandler </strong>interface. This handler is initialized with the route data, containing the matching information.</p>
<p>When called, the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.webhost.httpcontrollerhandler(v=vs.108).aspx">HttpControllerHandler</a> on its <strong>BeginProcessRequest</strong> method performs the following actions:</p>
<ol>
<li>Creates a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> instance from the current <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx">HttpContext</a>; </li>
<li>Creates an <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> using the configuration referenced by <a href="http://msdn.microsoft.com/en-us/library/system.web.http.globalconfiguration.configuration(v=vs.108).aspx">GlobalConfiguration.Configuration</a> and then pushes the new `<a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a>` into the server pipeline. </li>
</ol>
<p>After the request is receive by the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> instance, it enters the host independent phase of the processing (the Web API new pipeline).</p>
<p>The following diagram summarizes the route resolution process and the dispatch into the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> instance (the message handler pipeline). </p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/aspnethosting.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="AspNetHosting" border="0" alt="AspNetHosting" src="http://pfelix.files.wordpress.com/2012/03/aspnethosting_thumb.png?w=578&#038;h=631" width="578" height="631" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/306/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=306&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/vyGfv_bGXIM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/03/07/asp-net-web-api-web-hosting/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/aspnethosting_thumb.png" medium="image">
			<media:title type="html">AspNetHosting</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/03/07/asp-net-web-api-web-hosting/</feedburner:origLink></item>
		<item>
		<title>ASP.NET Web API: in-memory hosting</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/QTkHA7C7Rwk/</link>
		<comments>http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 20:05:09 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=302</guid>
		<description><![CDATA[One of the nice features in the new ASP.NET Web API is in-memory hosting, i.e., the possibility to directly connect a HttpClient to the server-side runtime, without any network usage or HTTP message serialization: In the above code, notice how the HttpClient is initialized with the HttpServer, establishing the direct client-server connection. This feature is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=302&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>One of the nice features in the new ASP.NET Web API is <em>in-memory hosting</em>, i.e., the possibility to directly connect a <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> to the server-side runtime, without any <em>network usage </em>or<em> </em>HTTP <em>message serialization</em>:</p>
<div style="display:inline;float:none;margin:0;padding:0;" class="wlWriterEditableSmartContent">
<pre style="white-space:normal;">
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
// additional config ...
var server = new HttpServer(config);
var client = new HttpClient(server);
var r = client.GetAsync("http://can.be.anything/resource")
</pre>
</div>
<p>In the above code, notice how the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> is initialized with the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a>, establishing the direct client-server connection.</p>
<p>This feature is relevant on integration or end-to-end testing scenarios, by decreasing the time required for a round-trip and avoiding the self-hosting complexity (e.g. URI access control).</p>
<p>This feature also illustrates an interesting symmetry between the client and server stacks, around the message handler concept, as described in the following paragraphs.</p>
<h6>Server side</h6>
<p>The <a href="https://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/">last post</a> described the <a href="http://www.asp.net/web-api">ASP.NET Web API</a> server-side processing architecture : what happens since a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> request is received until a response is produced.</p>
<p>As stated in that post, this processing architecture is composed by three layers: <em>hosting</em>, <em>message handler pipeline</em> and <em>controller handling</em>. The hosting layer </p>
<ul>
<li>translates HTTP requests, received from lower level APIs, into <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> instances; </li>
<li>pushes this messages into the above <em>message handler pipeline</em>, wrapped by a <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a>.&#160; Typically, at the end of this pipeline there is an handler that dispatches the messages to the chosen controller. </li>
</ul>
<p>Of special relevance is the fact that <a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpserver(v=vs.108).aspx">HttpServer</a> derives from <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v=vs.110).aspx">HttpMessageHandler</a> (composite pattern). </p>
<h6>Client side</h6>
<p>The architecture of the new <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> class was also described in a <a href="https://pfelix.wordpress.com/2012/01/11/the-new-net-httpclient-class/">previous post</a>, namely the fact that the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> internally uses a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v=vs.110).aspx">HttpMessageHandler</a> to compute the HTTP response, given the HTTP request.</p>
<p>&#160;</p>
<p><img style="display:block;float:none;margin-left:auto;margin-right:auto;" src="http://pfelix.files.wordpress.com/2012/01/httpclientandinnerhandler.png?w=720" /></p>
<p>&#160;</p>
<p>It is this symmetry - <a href="http://pfelix.files.wordpress.com/2012/01/httpclientandinnerhandler.png">HttpServer</a>&#160;<em>is</em> a message handler and <a href="http://wcf.codeplex.com/SourceControl/changeset/view/417c9a96fc24#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpClient.cs">HttpClient</a> <em>receives</em> a message handler - that allows the direct connection of the client to the server, bypassing the server side hosting layer, as showed in the following diagram.</p>
<p>&#160;</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/memoryhosting.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:block;float:none;margin-left:auto;border-top:0;margin-right:auto;border-right:0;padding-top:0;" title="MemoryHosting" border="0" alt="MemoryHosting" src="http://pfelix.files.wordpress.com/2012/03/memoryhosting_thumb.png?w=421&#038;h=403" width="421" height="403" /></a></p>
<p>Nice, isn’t it?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/302/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/302/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=302&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/QTkHA7C7Rwk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/01/httpclientandinnerhandler.png" medium="image" />

		<media:content url="http://pfelix.files.wordpress.com/2012/03/memoryhosting_thumb.png" medium="image">
			<media:title type="html">MemoryHosting</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/</feedburner:origLink></item>
		<item>
		<title>ASP.NET Web API Processing Architecture</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/ggkmPZS-zow/</link>
		<comments>http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 12:48:25 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=298</guid>
		<description><![CDATA[Introduction This post presents a first overview of the ASP.NET Web API processing architecture: what happens since a HTTP request is received until a response is produced. Processing Architecture The ASP.NET Web API processing architecture, represented in the following diagram, is composed by three layers: hosting, message handler pipeline and controller handling. Hosting The lower [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=298&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h3>Introduction</h3>
<p>This post presents a first overview of the ASP.NET Web API processing architecture: what happens since a HTTP request is received until a response is produced. </p>
<h3>Processing Architecture</h3>
<p>The <a href="http://www.asp.net/web-api">ASP.NET Web API</a> processing architecture, represented in the following diagram, is composed by three layers: <em>hosting</em>, <em>message handler pipeline</em> and <em>controller handling</em>.</p>
<p><a href="http://pfelix.files.wordpress.com/2012/03/processing-architecture.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="Processing.Architecture" border="0" alt="Processing.Architecture" src="http://pfelix.files.wordpress.com/2012/03/processing-architecture_thumb.png?w=680&#038;h=654" width="680" height="654" /></a></p>
<h4>Hosting</h4>
<p>The lower layer is responsible for the Web API <em>hosting</em>, i.e., the interface between Web API and an underlying <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP</a> handling runtime.&#160; Succinctly, this layer is responsible for creating <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> instances, and then pushing them into the upper message handler pipeline. The hosting layer is also responsible for processing the <a href="http://wcf.codeplex.com/SourceControl/changeset/view/27fc5d70d895#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.Net.Http%2fHttpResponseMessage.cs">HttpResponseMessage</a> returned back from this handler pipeline.</p>
<p>Currently, there are two “out-of-the-box” hosting options: self-hosting and web hosting, i.e., hosting on top of the ASP.NET <em>classical</em> pipeline.</p>
<p><em>Self-hosting</em> is based on a pump that retrieves WCF <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx">Message</a> instances from a WCF channel stack, converts them into <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a> instances and then push those into the upper message handler pipeline. </p>
<p><em>Web-hosting</em> is based on a specific <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpasynchandler(v=vs.100).aspx">IHttpAsyncHandler</a>, named <a href="http://msdn.microsoft.com/en-us/library/system.web.http.webhost.httpcontrollerhandler(v=vs.108).aspx">HttpControllerHandler</a>, that converts <a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.aspx">HttpRequest</a> instances into <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage(v=vs.110).aspx">HttpRequestMessage</a>.</p>
<p>The Web API hosting is not limited to these two options. There are already some additional hosts, contributed by the community:</p>
<ul>
<li><a href="https://twitter.com/#!/loudej">Louis DeJardin</a> <a href="http://whereslou.com/2012/02/20/gate-adds-owin-support-for-the-new-asp-net-web-api-beta">created a host</a> on top of <a href="http://owin.org/">OWIN</a>.</li>
<li>I’ve created a <a href="https://github.com/pmhsfelix/WebApi.Explorations.ServiceBusRelayHost">host</a> based on the <a href="https://www.windowsazure.com/en-us/develop/net/how-to-guides/service-bus-relay/">Azure Service Bus relaying</a>. </li>
</ul>
<h4>Message Handler Pipeline</h4>
<p>The middle layer is composed by a message handler pipeline, similar to <a href="https://pfelix.wordpress.com/2011/08/09/wcf-web-apimessage-handlers/">the one that existed on WCF Web API</a>. This pipeline is exposed by the <a href="http://msdn.microsoft.com/en-us/library/hh834055(v=vs.108).aspx">HttpServer</a> class, which also extends <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v=vs.110).aspx">HttpMessageHandler</a> (composite pattern).</p>
<p>This pipeline provides the extensibility point for “middleware” <a href="http://codebetter.com/glennblock/2011/05/17/message-handlers-vs-operation-handlers-which-one-to-use-2/">addressing cross-cutting concerns</a> such as: logging, HTTP authentication, HTTP method translation, …</p>
<p>Usually, at the top of this pipeline, there is a special handler: the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.dispatcher.httpcontrollerdispatcher(v=vs.108).aspx">HttpControllerDispatcher</a>. This handler is responsible for obtaining and <a href="http://msdn.microsoft.com/en-us/library/system.web.http.controllers.ihttpcontroller.executeasync(v=vs.108).aspx">calling</a> a <a href="http://msdn.microsoft.com/en-us/library/system.web.http.controllers.ihttpcontroller(v=vs.108).aspx">controller</a> to handle the request.</p>
<p>The presence of this <a href="http://msdn.microsoft.com/en-us/library/system.web.http.dispatcher.httpcontrollerdispatcher(v=vs.108).aspx">HttpControllerDispatcher</a> is only required when using the <em>controller-based programming model </em>(<a href="http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller(v=vs.108).aspx">ApiController</a> derived classes). It is also possible to mount a completely different model, just by replacing the pipeline’s top message handler.</p>
<h4>Controller Handling</h4>
<p>Finally, the upper layer corresponds to the controller specific processing, namely:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.http.controllers.apicontrolleractionselector(v=vs.108).aspx">Action selection</a>;</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.http.filters.iactionfilter(v=vs.108).aspx">Filter</a> execution;</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.http.modelbinding.imodelbinder(v=vs.108).aspx">Model binding</a>;</li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.http.controllers.apicontrolleractioninvoker(v=vs.108).aspx">Action invocation</a>;</li>
<li>Response content creation via <a href="http://msdn.microsoft.com/en-us/library/system.net.http.formatting.mediatypeformatter(v=vs.108).aspx">formatters</a>.</li>
</ul>
<p>This processing is done inside the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller(v=vs.108).aspx">ApiController</a> instance, called by the <a href="http://msdn.microsoft.com/en-us/library/system.web.http.dispatcher.httpcontrollerdispatcher(v=vs.108).aspx">HttpControllerDispatcher</a>.</p>
<h3>Final Remarks</h3>
<p>Future posts will address each one of this layers in more details. Until then, feel free to use the comments.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/298/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/298/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=298&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/ggkmPZS-zow" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/03/processing-architecture_thumb.png" medium="image">
			<media:title type="html">Processing.Architecture</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-processing-architecture/</feedburner:origLink></item>
		<item>
		<title>Enabling HTTPS with self-hosted ASP.NET Web API</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/-_HuaX9-Wh4/</link>
		<comments>http://pfelix.wordpress.com/2012/02/26/enabling-https-with-self-hosted-asp-net-web-api/#comments</comments>
		<pubDate>Sun, 26 Feb 2012 01:12:52 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>
		<category><![CDATA[HTTPS]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=287</guid>
		<description><![CDATA[In a previous post, I showed how to  self-host ASP.NET Web API. This post shows how to change that example in order to enable HTTPS support. On an elevated console (“Run as administrator”), execute “netsh http add urlacl url=https://+:4443/ user=&#60;your user name&#62;”, to allow the running user to listen on port 4443 using HTTPS (note the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=287&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In a <a href="https://pfelix.wordpress.com/2012/02/26/self-hosting-asp-net-web-api/">previous post</a>, I showed how to <span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;"> self-host </span><a style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;" href="http://www.asp.net/web-api">ASP.NET Web API</a><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;">. This post shows how to change that example in order to enable HTTPS support.</span></p>
<ol>
<li><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;"><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;"><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;">On an elevated console (“Run as administrator”), execute “</span><strong>netsh http add urlacl url=https://+:4443/ user=&lt;your user name&gt;</strong><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;">”, to allow the running user to listen on port 4443 using HTTPS (note the use of ‘https’ instead of ‘<a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">http</a>’ in the above command).</span></span></span></li>
<li><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;"><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;"><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;">Also on an elevated console, register the server certificate by running</span></span></span>
<p style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;"><strong>netsh http add sslcert ipport=0.0.0.0:</strong><em>port</em> <strong>certhash</strong>=<em>thumbprint</em> <strong>appid={</strong><em>app-guid</em><strong>} </strong>where</p>
<ul style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;">
<li style="margin:0 0 10px;padding:0;"><em>port</em> is the listening port (e.g. 4443); the special IP address 0.0.0.0 matches any IP address for the local machine;</li>
<li style="margin:0 0 10px;padding:0;"><em>thumbprint</em> is the certificate’s SHA-1 hash, represented in hexadecimal;</li>
<li style="margin:0 0 10px;padding:0;"><em>app-guid</em> is any GUID (e.g. {00000000-0000-0000-0000-000000000000}) , used to identity the owning application.</li>
</ul>
</li>
<li>In the <a href="https://pfelix.wordpress.com/2012/02/26/self-hosting-asp-net-web-api/">previous post’s</a> <strong>Main</strong> method, replace the <strong>HttpSelfHostConfiguration</strong> class with the new <strong>MyHttpsSelfHostConfiguration</strong> class, containing the following code.</li>
<li>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6b280800-9f08-4419-a9e4-cedb46b3882c" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
class MyHttpsSelfHostConfiguration : HttpSelfHostConfiguration
{
    public MyHttpsSelfHostConfiguration(string baseAddress) : base(baseAddress){}
    public MyHttpsSelfHostConfiguration(Uri baseAddress) : base(baseAddress){}
    protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
    {
        httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
        return base.OnConfigureBinding(httpBinding);
    }
}

</pre>
</div>
</li>
<li>Change the base address passed to the <strong>MyHttpsSelfHostConfiguration</strong> constructor: <strong>var config = new MyHttpsSelfHostConfiguration(&#8220;<a href="https://localhost:4443&#038;#8243" rel="nofollow">https://localhost:4443&#038;#8243</a>;);</strong></li>
<li><span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;">Run the program, open a browser and access </span><a style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;" href="https://localhost:4443/hello">https://localhost:4443/hello</a><a href="http://pfelix.files.wordpress.com/2012/02/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://pfelix.files.wordpress.com/2012/02/image_thumb1.png?w=678&#038;h=220" alt="image" width="678" height="220" border="0" /></a></li>
</ol>
<p>That’s it: <span style="widows:2;text-transform:none;background-color:#ffffff;text-indent:0;letter-spacing:normal;display:inline!important;"> you now have a self-hosted ASP.NET Web API server, using the secure HTTPS protocol.</span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/287/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=287&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/-_HuaX9-Wh4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/02/26/enabling-https-with-self-hosted-asp-net-web-api/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/02/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/02/26/enabling-https-with-self-hosted-asp-net-web-api/</feedburner:origLink></item>
		<item>
		<title>Self-hosting ASP.NET Web API</title>
		<link>http://feedproxy.google.com/~r/pfelix/~3/gsbpbr-67E0/</link>
		<comments>http://pfelix.wordpress.com/2012/02/26/self-hosting-asp-net-web-api/#comments</comments>
		<pubDate>Sun, 26 Feb 2012 00:03:44 +0000</pubDate>
		<dc:creator>pedrofelix</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[asp.net web api]]></category>

		<guid isPermaLink="false">https://pfelix.wordpress.com/?p=283</guid>
		<description><![CDATA[Just a simple example, showing how to self-host ASP.NET Web API. On an elevated console (“Run as administrator”), execute “netsh http add urlacl url=http://+:8080/ user=&#60;your user name&#62;”, to allow the running user to listen on port 8080. On Visual Studio, create a “Console Application” project. Change the project’s Target Framework property from “.NET Framework 4 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=283&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Just a simple example, showing how to self-host <a href="http://www.asp.net/web-api">ASP.NET Web API</a>.</p>
<ol>
<ol>
<li>On an elevated console (“Run as administrator”), execute “<strong>netsh http add urlacl url=http://+:8080/ user=&lt;your user name&gt;</strong>”, to allow the running user to listen on port 8080.</li>
<li>On Visual Studio, create a “Console Application” project.</li>
<li>Change the project’s <em>Target Framework</em> property from “.NET Framework 4 Client Profile” to “.NET Framework 4 profile”.</li>
<li>Install the <a href="http://nuget.org/packages/AspNetWebApi.SelfHost/4.0.20126.16343">AspNetWebApi.Selfhost</a> NuGet package</li>
<li>Create a <em>public</em> <strong>ApiController</strong> derived class.</li>
</ol>
</ol>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a8f15bd6-7122-442c-9f01-1305e338b279" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
public class HelloController : ApiController
{
  public HttpResponseMessage Get()
  {
    return new HttpResponseMessage
        {
          Content = new StringContent(&quot;Hello HTTP&quot;)
        };
  }
}
</pre>
</div>
<ol>
<ol>
<li>In the program’s <strong>Main</strong> method,
<ol>
<li>Create a <strong>HttpSelfHostConfiguration</strong>, initialized with the base address.</li>
<li>Add the default route: <strong>MapHttpRoute(&#8220;default&#8221;, &#8220;{controller}/{id}&#8221;, new { id = RouteParameter.Optional });</strong></li>
<li>Create a <strong>HttpSelfHostServer</strong>, initialized with the above configuration object.</li>
<li>Open the server, bearing in mind that the <strong>OpenAsync</strong> method is asynchronous.</li>
</ol>
</li>
</ol>
</ol>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:7631ce65-08c0-4f42-9099-5f6eba111bd2" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">
<pre class="brush: csharp; title: ; notranslate">
static void Main(string[] args)
{
  var config = new HttpSelfHostConfiguration(&quot;http://localhost:8080&quot;);
  config.Routes.MapHttpRoute(&quot;default&quot;, &quot;{controller}/{id}&quot;, new { id = RouteParameter.Optional });
  var server = new HttpSelfHostServer(config);
  server.OpenAsync().Wait();

  Console.WriteLine(&quot;Server is opened&quot;);
  Console.ReadKey();

</pre>
</div>
<ol>
<li>Run the program, open a browser and access <a href="http://localhost:8080/hello">http://localhost:8080/hello</a>.</li>
</ol>
<p><a href="http://pfelix.files.wordpress.com/2012/02/image.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="image" src="http://pfelix.files.wordpress.com/2012/02/image_thumb.png?w=426&#038;h=278" alt="image" width="426" height="278" border="0" /></a></p>
<p>That’s it. You now have a self-hosted ASP.NET Web API server.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pfelix.wordpress.com/283/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pfelix.wordpress.com/283/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pfelix.wordpress.com&#038;blog=3662583&#038;post=283&#038;subd=pfelix&#038;ref=&#038;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/pfelix/~4/gsbpbr-67E0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pfelix.wordpress.com/2012/02/26/self-hosting-asp-net-web-api/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/69d8b493312a1ed70943abf6cc2dcf72?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">pedrofelix</media:title>
		</media:content>

		<media:content url="http://pfelix.files.wordpress.com/2012/02/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	<feedburner:origLink>http://pfelix.wordpress.com/2012/02/26/self-hosting-asp-net-web-api/</feedburner:origLink></item>
	</channel>
</rss>
