<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.codeville.net/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.codeville.net/~d/styles/itemcontent.css" type="text/css" media="screen"?><!-- generator="wordpress/2.3.1" --><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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Steve Sanderson's blog</title>
	<link>http://blog.codeville.net</link>
	<description>mostly about ASP.NET MVC</description>
	<pubDate>Fri, 07 Nov 2008 15:58:37 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.codeville.net/SteveCodeville" type="application/rss+xml" /><item>
		<title>Speeding up communication between Firefox and Visual Studio’s built-in web server</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/445349910/</link>
		<comments>http://blog.codeville.net/2008/11/07/speeding-up-communication-between-firefox-and-visual-studios-built-in-web-server/#comments</comments>
		<pubDate>Fri, 07 Nov 2008 10:35:08 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Development process]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/11/07/speeding-up-communication-between-firefox-and-visual-studios-built-in-web-server/</guid>
		<description><![CDATA[ Has anyone else noticed that, during development, if you use Firefox to browse a site hosted in Visual Studio 2005/2008’s built-in web server (WebDev.WebServer.Exe), it’s really, just, so, excruciatingly … slow?
Oh it’s fine if you use Internet Explorer. Or Chrome for that matter. But every request issued from Firefox to WebDev.WebServer.Exe seems to have [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.codeville.net/wp-content/uploads/2008/11/image.png"><img title="image" style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="244" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/11/image-thumb.png" width="244" align="right" border="0" /></a> Has anyone else noticed that, during development, if you use Firefox to browse a site hosted in Visual Studio 2005/2008’s built-in web server (WebDev.WebServer.Exe), it’s really, just, so, excruciatingly … slow?</p>
<p>Oh it’s fine if you use Internet Explorer. Or Chrome for that matter. But every request issued from Firefox to WebDev.WebServer.Exe seems to have about a full second of lag added. If your pages host multiple images and CSS files, it’s intolerable.</p>
<h4>It works on your machine</h4>
<p>What’s that you say – you haven’t experienced this problem? Lucky you! I’ve asked other developers about this, and they all claim it’s fine on their machine too. And a quick Google search doesn’t turn up any other reports of the issue.</p>
<p>But I’ve had four different physical development PCs in the last couple of years, running three major different OS versions, two major different versions of Visual Studio and two major different versions of Firefox, and still have been wading through treacle every single time! Firefox is way faster communicating with servers on the other side of the planet than with this particular web server hosted on the same PC. What gives?</p>
<p>The conspiracy theorist in me even wondered if some evil person in Microsoft had hard-coded this behaviour into VS, intending to discourage web developers from working exclusively in Firefox. I confess I even changed my Firefox UserAgent string to match MSIE, but that didn’t help.</p>
<h4>The solution</h4>
<p>Finally! It turns out to be something to do with IPv6. I don’t know whether the problem is in Firefox or in WebDev.WebServer.Exe, but disabling Firefox’s IPv6 support is like cutting off the ball and chain. Suddenly, communication with the local server is back to the blistering pace you’d expect.</p>
<p>All you need now is <a href="http://en.opensuse.org/Disable_IPv6_for_Firefox" target="_blank">instructions for disabling Firefox’s IPv6 support</a>.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=Xh22n"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=Xh22n" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=pZr0N"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=pZr0N" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=Qi30n"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=Qi30n" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=27nzN"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=27nzN" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/445349910" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/11/07/speeding-up-communication-between-firefox-and-visual-studios-built-in-web-server/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/11/07/speeding-up-communication-between-firefox-and-visual-studios-built-in-web-server/</feedburner:origLink></item>
		<item>
		<title>App Areas in ASP.NET MVC, take 2</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/443240318/</link>
		<comments>http://blog.codeville.net/2008/11/05/app-areas-in-aspnet-mvc-take-2/#comments</comments>
		<pubDate>Wed, 05 Nov 2008 13:31:01 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/11/05/app-areas-in-aspnet-mvc-take-2/</guid>
		<description><![CDATA[So the discussion continues: How do you partition an ASP.NET MVC application into separate “areas” or “modules” (e.g., blog module, e-commerce module, forums module), then compose a finished app from those areas or modules? 
Phil Haack, ASP.NET MVC program manager, just posted a prototype application structured in that way. It’s a really neat solution, and [...]]]></description>
			<content:encoded><![CDATA[<p>So the discussion continues: How do you partition an ASP.NET MVC application into separate “areas” or “modules” (e.g., blog module, e-commerce module, forums module), then compose a finished app from those areas or modules? </p>
<p>Phil Haack, ASP.NET MVC program manager, <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" target="_blank">just posted a prototype application</a> structured in that way. It’s a really neat solution, and overcomes a number of issues that others, <a href="http://blog.codeville.net/2008/07/30/partitioning-an-aspnet-mvc-application-into-separate-areas/" target="_blank">including myself</a>, have experienced when trying to do it previously.</p>
<p>In this post, I’m going to take Phil’s prototype and tweak it in a few ways to my liking. That’s not to say that there’s anything wrong with his design, but only that I want to throw in some extra ideas that might make it even slicker in some cases.</p>
<h4>How it works</h4>
<p>The mechanism as given comes in two parts:</p>
<ul>
<li><strong>Routing configuration</strong>: There’s an extension method on RouteCollection called MapAreas() which lets you register a URL pattern for multiple areas. You pass it a URL pattern, a controller “root namespace”, and an array of area names. It prefixes “{area}/” to your URL pattern, and for each area name, it registers a route entry that targets controllers who live in the namespace given by:&#160;
<div align="center" style="margin-bottom:1em;">(root namespace + “.Areas.” + area name + “.Controllers”)</div>
</li>
<li><strong>View engine</strong>: There’s a special view engine called AreaViewEngine that uses a built-in convention to look for view templates in an area-specific folder. </li>
</ul>
<p><u>Don’t worry if you don’t understand this</u>. If you <a href="http://haacked.com/code/AreasDemo.zip" target="_blank">download Phil’s prototype</a> and try it, you’ll find it’s all straightforward enough.</p>
<p>It works very nicely, and it uses a clever trick with route defaults and constraints so that when you’re generating outbound URLs, you can link to controllers/actions in any area by specifying the area name in your Html.RouteLink() call, or you can link to controllers/actions within the same area using a normal Html.RouteLink() call that doesn’t specify any area name.</p>
<h4>Suggestions for enhancement</h4>
<p>I’m not going to touch the view engine part of the prototype at all. All I want to achieve is a configuration system that’s slightly more natural (for me) and a modified set of conventions and rules that are a bit more flexible. Here’s how I’d like a simple areas routing configuration to look:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #008000;">// Routing config for the blogs area</span>
routes.<span style="color: #0000FF;">CreateArea</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;blogs&quot;</span>, <span style="color: #A31515;">&quot;AreasDemo.Areas.Blogs.Controllers&quot;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;blogs/{controller}/{action}&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #008000;">// Routing config for the forums area</span>
routes.<span style="color: #0000FF;">CreateArea</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;forums&quot;</span>, <span style="color: #A31515;">&quot;AreasDemo.Areas.Forums.Controllers&quot;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;forums/{controller}/{action}&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #008000;">// Routing config for the root area</span>
routes.<span style="color: #0000FF;">CreateArea</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;root&quot;</span>, <span style="color: #A31515;">&quot;AreasDemo.Controllers&quot;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;{controller}/{action}&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>… and here’s an example of a very slightly more complex configuration:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #008000;">// Routing config for the blogs area</span>
routes.<span style="color: #0000FF;">CreateArea</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;blogs&quot;</span>, <span style="color: #A31515;">&quot;AreasDemo.Areas.Blogs.Controllers&quot;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;SpecialUrlForPosts&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Posts&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;blg/{controller}/{action}/{id}&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> action = <span style="color: #A31515;">&quot;Index&quot;</span>, controller = <span style="color: #A31515;">&quot;Home&quot;</span>, id = <span style="color: #A31515;">&quot;&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #008000;">// Routing config for the forums area</span>
routes.<span style="color: #0000FF;">CreateArea</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;forums&quot;</span>, <span style="color: #A31515;">&quot;AreasDemo.Areas.Forums.Controllers&quot;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;myforums/SecretAdminZone/{action}&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Admin&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>,
&nbsp;
    <span style="color: #008000;">// Equally possible to construct routes using &quot;new Route()&quot; syntax too</span>
    <span style="color: #0000FF;">new</span> Route<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;myforums/{controller}/{action}&quot;</span>, <span style="color: #0000FF;">new</span> MvcRouteHandler<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        Defaults = <span style="color: #0000FF;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #008000;">// Routing config for the root area</span>
routes.<span style="color: #0000FF;">CreateArea</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;root&quot;</span>, <span style="color: #A31515;">&quot;AreasDemo.Controllers&quot;</span>,
    routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">null</span>, <span style="color: #A31515;">&quot;{controller}/{action}&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>The point to notice is that each area is configured independently of the others, which for me feels more natural than defining a single URL pattern that for some reason applies to all areas.</p>
<p>It turns out to be dead easy to make it work like this. All you need is this simple CreateArea() extension method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> <span style="color: #0000FF;">void</span> CreateArea<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span> RouteCollection routes, <span style="color: #0000FF;">string</span> areaName, <span style="color: #0000FF;">string</span> controllersNamespace, <span style="color: #0000FF;">params</span> Route<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> routeEntries<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> route <span style="color: #0000FF;">in</span> routeEntries<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>route.<span style="color: #0000FF;">Constraints</span> == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span> route.<span style="color: #0000FF;">Constraints</span> = <span style="color: #0000FF;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>route.<span style="color: #0000FF;">Defaults</span> == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span> route.<span style="color: #0000FF;">Defaults</span> = <span style="color: #0000FF;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>route.<span style="color: #0000FF;">DataTokens</span> == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span> route.<span style="color: #0000FF;">DataTokens</span> = <span style="color: #0000FF;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        route.<span style="color: #0000FF;">Constraints</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;area&quot;</span>, areaName<span style="color: #000000;">&#41;</span>;
        route.<span style="color: #0000FF;">Defaults</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;area&quot;</span>, areaName<span style="color: #000000;">&#41;</span>;
        route.<span style="color: #0000FF;">DataTokens</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;namespaces&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #0000FF;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> controllersNamespace <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>!routes.<span style="color: #0000FF;">Contains</span><span style="color: #000000;">&#40;</span>route<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">// To support &quot;new Route()&quot; in addition to &quot;routes.MapRoute()&quot;</span>
            routes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>route<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Apart from that, there’s no difference from the original prototype (well, you can delete the original prototype’s MapAreas() and MapRootArea() methods: they’re no longer used).</p>
<h4>Benefits</h4>
<p>How does this differ from the original prototype? What conventions have changed?</p>
<ul>
<li><strong>URL patterns are no longer forced to start with the area name</strong> (though they can if you want). Within a single area, you can have some URLs that start with the area name, and some that don’t. </li>
<li>In fact, <strong>URL patterns are now totally independent of area names</strong>, which means your area names can simply be internal code words for software modules, never seen by the public. If that’s what you want. </li>
<li><strong>Controller namespaces are independent of area names</strong>, and they don’t even have to be constant within a single area. Pick your own convention and follow it. </li>
<li>You can&#160; <strong>configure each area’s routes in a separate block of code</strong>, using a sweet DRY syntax, which for me feels more natural than having a single method call that registers routes across all areas. </li>
<li>You <strong>don’t need any special code or configuration for the “root” area</strong> – that’s just another area like the others, usually just with shorter URL patterns. </li>
<li><strong>You can keep using the familiar <em>routes.MapRoute()</em> and <em>new Route()</em></strong><em> </em>ways of building route entries, merely wrapping up groups of them in CreateArea() calls. No significant new API. </li>
</ul>
<p>Apart from this, it uses almost exactly the same mechanism as in the original prototype.</p>
<h4>Drawbacks</h4>
<p>If enforcing conventions is your thing, then you might not appreciate the extra flexibility that comes with these changes. </p>
<p>Also, when you do cross-area links, you have to be careful to specify a controller name and not just assume the default controller will be used. Otherwise, the generated URL might reuse the current request’s controller name, which might not even exist in the destination area. This is because of an obscure technicality in how URL generation works (it doesn’t affect Phil’s original design because of how he requires all URLs to start with an “{area}” segment).</p>
<p>This isn’t worth explaining in detail – all I’ll say is that the solution is simply to make sure your cross-area links always specify a controller name. Of course, you almost certainly should be doing that anyway, because it would be very weird to link just to an action name on a different area without being clear about which controller hosts that action.</p>
<h4>Summary</h4>
<p>ASP.NET MVC continues to impress me with its flexibility. If you want to structure your app in terms of “modules” or “areas”, it doesn’t take much code to enable it. Phil’s approach to areas is the neatest I’ve seen so far. Personally I like the tweaks I’ve suggested above, but it’s subjective and you can do things your own way.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=VvRcn"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=VvRcn" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=5xaKN"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=5xaKN" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=ryzYn"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=ryzYn" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=hRzCN"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=hRzCN" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/443240318" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/11/05/app-areas-in-aspnet-mvc-take-2/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/11/05/app-areas-in-aspnet-mvc-take-2/</feedburner:origLink></item>
		<item>
		<title>DDD7 talk: “ASP.NET MVC - Show me the code!”</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/428468158/</link>
		<comments>http://blog.codeville.net/2008/10/22/ddd7-talk-aspnet-mvc-show-me-the-code/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 11:30:48 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Speaking]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/10/22/ddd7-talk-aspnet-mvc-show-me-the-code/</guid>
		<description><![CDATA[Just a quick announcement for UK readers: if you&#8217;re going to DDD7, you might be interested in the following session I&#8217;m presenting.



What:
ASP.NET MVC - Show me the code! (60 minutes)


Where/when:
DDD7 at Microsoft&#8217;s Reading campus, Saturday 22nd November 2008, 10.40am in &#8220;Chicago 1&#8243; room


Description:

Microsoft&#8217;s new MVC-based web development framework has got the bloggers all excited - [...]]]></description>
			<content:encoded><![CDATA[<p>Just a quick announcement for UK readers: if you&#8217;re going to DDD7, you might be interested in the following session I&#8217;m presenting.</p>
<div style="border:1px solid black; background-color: silver; padding: 1em; margin-bottom:1em;">
<table border="0" align="center">
<tr valign="baseline">
<td align="right"><i>What:</i></td>
<td><b>ASP.NET MVC - Show me the code!</b> (60 minutes)</td>
</tr>
<tr valign="baseline">
<td align="right"><i>Where/when:</i></td>
<td>DDD7 at Microsoft&#8217;s Reading campus, Saturday 22nd November 2008, 10.40am in &#8220;Chicago 1&#8243; room</td>
</tr>
<tr valign="baseline">
<td align="right"><i>Description:</i></td>
<td>
Microsoft&#8217;s new MVC-based web development framework has got the bloggers all excited - but what&#8217;s it like to use? What&#8217;s wrong with classic ASP.NET, and how does MVC do better or worse? In this session we build a small web application, comparing the development experience with classic ASP.NET. See MVC architecture, clean URLs, unit testing, tight HTML, and simple ajax at work.
</td>
</tr>
</table>
</div>
<p>
<a href="http://www.developerday.co.uk/ddd/default.asp">DeveloperDeveloperDeveloper! Day</a> is a <b>free</b> one-day event run by the UK .NET community for the UK .NET community. It&#8217;s among the largest such events in the UK, so I&#8217;m excited to be presenting a session! Judging by the <a href="http://www.developerday.co.uk/ddd/agendaddd7lineup.asp">list of speakers</a> and the event&#8217;s reputation, quality should be pretty high, and the technical content should be pretty deep.
</p>
<p>
<a href="http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032393874&#038;Culture=en-GB">Registration has just opened</a>, but be warned: it will likely sell out within the next 24 hours&#8230;</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=1ednm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=1ednm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=YIMHM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=YIMHM" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=vnYem"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=vnYem" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=8p0lM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=8p0lM" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/428468158" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/10/22/ddd7-talk-aspnet-mvc-show-me-the-code/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/10/22/ddd7-talk-aspnet-mvc-show-me-the-code/</feedburner:origLink></item>
		<item>
		<title>Partial Output Caching in ASP.NET MVC</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/421857581/</link>
		<comments>http://blog.codeville.net/2008/10/15/partial-output-caching-in-aspnet-mvc/#comments</comments>
		<pubDate>Wed, 15 Oct 2008 18:46:16 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/10/15/partial-output-caching-in-aspnet-mvc/</guid>
		<description><![CDATA[The ASP.NET platform provides two major caching facilities:

Data caching, which lets you cache arbitrary .NET objects in an HttpContext&#8217;s Cache collection. You can specify expiration rules and cache entry priorities.
Output caching, which tells pages and user controls to cache their own rendered output and re-use it on subsequent requests. This is designed to sit neatly [...]]]></description>
			<content:encoded><![CDATA[<p>The ASP.NET platform provides two major caching facilities:</p>
<ul>
<li><em>Data caching</em>, which lets you cache arbitrary .NET objects in an HttpContext&#8217;s Cache collection. You can specify expiration rules and cache entry priorities.
<li><em>Output caching</em>, which tells pages and user controls to cache their own rendered output and re-use it on subsequent requests. This is designed to sit neatly in WebForms&#8217; system of server control hierarchies.</li>
</ul>
<p>Data caching continues to work perfectly well in ASP.NET MVC, because it&#8217;s just about getting objects in and out of a collection, and isn&#8217;t specific to any particular UI technology.</p>
<p>If only output caching was so simple! ASP.NET&#8217;s output caching facility is deeply stuck in WebForms thinking, which makes it problematic in ASP.NET MVC. You <em>could </em>try to use ASP.NET output caching with ASP.NET MVC, but then you&#8217;d have the following issues:</p>
<ul>
<li><em>No usable support for partial caching.</em> ASP.NET output caching can cache complete responses or individual server controls, but hang on: we&#8217;re not using server controls in ASP.NET MVC, so all that&#8217;s left is complete response caching.
<li><em>Bypasses authorization and other filters.</em> ASP.NET output caching runs very early in the request-processing pipeline (see HttpApplication&#8217;s ResolveRequestCache event), long before MVC comes in with its controllers, actions, and filters. It can&#8217;t behave like an action filter is supposed to. <i>See update below.</i></li>
</ul>
<p>Unfortunately, the [OutputCache] filter that ships with ASP.NET MVC is merely a thin wrapper around ASP.NET output caching, so it has exactly those problems. The MVC team have explained that they&#8217;re aware of the issues, but it&#8217;s <a href="http://forums.asp.net/t/1332238.aspx" target="_blank">very difficult</a> to make ASP.NET output <a href="http://www.codeplex.com/aspnet/WorkItem/View.aspx?WorkItemId=2062" target="_blank">caching fit</a> into <a href="http://forums.asp.net/t/1333752.aspx" target="_blank">MVC&#8217;s design</a>, and they are focusing on other things first. And personally I&#8217;m happy with that: I&#8217;d rather see a finished 1.0 RTM release this year than fuss about output caching.</p>
<div style="border:1px solid black; background-color:silver">
<p><b>Update:</b> Since the Beta release, the [Authorize] filter now does some clever trickery to co-operate with ASP.NET output caching. Specifically, it registers a delegate using HttpCachePolicy.AddValidationCallback(), so that it can intercept future cache hits and tell ASP.NET output caching not to use the cache when [Authorize] would reject the request. This solves the problem of ASP.NET output caching bypassing the [Authorize] filter. If you&#8217;re going to write your own authorization filter, be sure to derive it from AuthorizeAttribute so you can inherit this useful behaviour.</p>
<p>Note that this doesn&#8217;t stop ASP.NET output caching from bypassing any of your other action filters, and it doesn&#8217;t add any support for partial caching. If that&#8217;s a problem for you then consider using [ActionOutputCache] (below) instead.</p>
</div>
<h4>Fixing it ourselves</h4>
<p>One reason why I don&#8217;t mind [OutputCache]&#8217;s limitations so much is that ASP.NET MVC is extremely extensible, and without too much trouble we can replace the output caching system with something new and more suitable. </p>
<p>We can quite easily create a new caching filter that captures actions&#8217; output and uses ASP.NET&#8217;s data caching facility to store it for next time. This filter will fit properly into the MVC pipeline, not strangely bypassing authorization or other earlier filters (it will run at the right time in whatever ordered set of filters you&#8217;ve using). And if you&#8217;re using something like the <a href="http://blog.codeville.net/?p=116" target="_blank">PartialRequest system for widgets that I described yesterday</a>, it will naturally let you cache PartialRequests&#8217; output separately from the actions that host them, which is also known as partial output caching.</p>
<p>I must first acknowledge that the following code is very similar to the <a href="http://blog.maartenballiauw.be/post/2008/06/26/Creating-an-ASPNET-MVC-OutputCache-ActionFilterAttribute.aspx" target="_blank">custom output caching filter</a> that <a href="http://blog.maartenballiauw.be/" target="_blank">Maarten Balliauw</a> presented way back in June. The reason I think this warrants a whole new post is because the following code works better for partial caching with PartialRequest and with MVC Contrib&#8217;s subcontrollers, and because it would be good for more MVC developers to discover it. But Maarten was first to write a good blog post on this subject.</p>
<p>So here it is. Drop the following class somewhere in your MVC project:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> ActionOutputCacheAttribute : ActionFilterAttribute
<span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">// This hack is optional; I'll explain it later in the blog post</span>
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">static</span> MethodInfo _switchWriterMethod = <span style="color: #0000FF;">typeof</span><span style="color: #000000;">&#40;</span>HttpResponse<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetMethod</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;SwitchWriter&quot;</span>, <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Reflection</span>.<span style="color: #0000FF;">BindingFlags</span>.<span style="color: #0000FF;">Instance</span> | <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Reflection</span>.<span style="color: #0000FF;">BindingFlags</span>.<span style="color: #0000FF;">NonPublic</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">public</span> ActionOutputCacheAttribute<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">int</span> cacheDuration<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _cacheDuration = cacheDuration;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">int</span> _cacheDuration;
    <span style="color: #0000FF;">private</span> TextWriter _originalWriter;
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">string</span> _cacheKey;
&nbsp;
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">override</span> <span style="color: #0000FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext filterContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _cacheKey = ComputeCacheKey<span style="color: #000000;">&#40;</span>filterContext<span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">string</span> cachedOutput = <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span><span style="color: #000000;">&#41;</span>filterContext.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">Cache</span><span style="color: #000000;">&#91;</span>_cacheKey<span style="color: #000000;">&#93;</span>;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>cachedOutput != <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
            filterContext.<span style="color: #0000FF;">Result</span> = <span style="color: #0000FF;">new</span> ContentResult <span style="color: #000000;">&#123;</span> Content = cachedOutput <span style="color: #000000;">&#125;</span>;
        <span style="color: #0000FF;">else</span>
            _originalWriter = <span style="color: #000000;">&#40;</span>TextWriter<span style="color: #000000;">&#41;</span>_switchWriterMethod.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>HttpContext.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">Response</span>, <span style="color: #0000FF;">new</span> <span style="color: #0000FF;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0000FF;">new</span> HtmlTextWriter<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> StringWriter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">override</span> <span style="color: #0000FF;">void</span> OnResultExecuted<span style="color: #000000;">&#40;</span>ResultExecutedContext filterContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>_originalWriter != <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">// Must complete the caching</span>
        <span style="color: #000000;">&#123;</span>
            HtmlTextWriter cacheWriter = <span style="color: #000000;">&#40;</span>HtmlTextWriter<span style="color: #000000;">&#41;</span>_switchWriterMethod.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>HttpContext.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">Response</span>, <span style="color: #0000FF;">new</span> <span style="color: #0000FF;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> _originalWriter <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #0000FF;">string</span> textWritten = <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>StringWriter<span style="color: #000000;">&#41;</span>cacheWriter.<span style="color: #0000FF;">InnerWriter</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            filterContext.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">Response</span>.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>textWritten<span style="color: #000000;">&#41;</span>;
&nbsp;
            filterContext.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">Cache</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_cacheKey, textWritten, <span style="color: #0000FF;">null</span>, DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">AddSeconds</span><span style="color: #000000;">&#40;</span>_cacheDuration<span style="color: #000000;">&#41;</span>, Cache.<span style="color: #0000FF;">NoSlidingExpiration</span>, <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">Caching</span>.<span style="color: #0000FF;">CacheItemPriority</span>.<span style="color: #0000FF;">Normal</span>, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">string</span> ComputeCacheKey<span style="color: #000000;">&#40;</span>ActionExecutingContext filterContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">var</span> keyBuilder = <span style="color: #0000FF;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> pair <span style="color: #0000FF;">in</span> filterContext.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">Values</span><span style="color: #000000;">&#41;</span>
            keyBuilder.<span style="color: #0000FF;">AppendFormat</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;rd{0}_{1}_&quot;</span>, pair.<span style="color: #0000FF;">Key</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, pair.<span style="color: #0000FF;">Value</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> pair <span style="color: #0000FF;">in</span> filterContext.<span style="color: #0000FF;">ActionParameters</span><span style="color: #000000;">&#41;</span>
            keyBuilder.<span style="color: #0000FF;">AppendFormat</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ap{0}_{1}_&quot;</span>, pair.<span style="color: #0000FF;">Key</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, pair.<span style="color: #0000FF;">Value</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">return</span> keyBuilder.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now you can use [ActionOutputCache] instead of MVC&#8217;s built-in [OutputCache]. The advantage of [ActionOutputCache] is that it&#8217;s a fully native MVC action filter, and doesn&#8217;t rely on or inherit the problems of ASP.NET&#8217;s WebForms-oriented output caching technology. So, for example, [ActionOutputCache] plays nicely with MVC&#8217;s [Authorize] filter. <i>Update: Since the beta release, the built in [Authorize] and [OutputCache] filters now play nicely together too.</i></p>
<p>You can use [ActionOutputCache] to cache the output of any action method just like [OutputCache], but it&#8217;s perhaps most interesting when you combine it with the <a href="http://blog.codeville.net/?p=116" target="_blank">PartialRequests</a> method of rendering widgets (or use it with Html.RenderAction(), which isn&#8217;t compatible with the built-in [OutputCache]). Put an [ActionOutputCache] attribute on the widget&#8217;s action method (not on the action that hosts it), then you&#8217;ll have partial page caching, as shown in the following code.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> BlogController : Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>ActionOutputCache<span style="color: #000000;">&#40;</span><span style="color: #000000;">60</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">// Caches for 60 seconds</span>
    <span style="color: #0000FF;">public</span> ActionResult LatestPosts<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;currentTime&quot;</span><span style="color: #000000;">&#93;</span> = DateTime.<span style="color: #0000FF;">Now</span>;
        ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;posts&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #0000FF;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span>
            <span style="color: #A31515;">&quot;Here's a post&quot;</span>,
            <span style="color: #A31515;">&quot;Here's another post. Marvellous.&quot;</span>,
            <span style="color: #A31515;">&quot;Programmer escapes from custody&quot;</span>
        <span style="color: #000000;">&#125;</span>;
        <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p><a href="http://blog.codeville.net/wp-content/uploads/2008/10/image1.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="307" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/10/image-thumb1.png" width="626" border="0"></a>&nbsp;
<p>This is great if your widget displays some relatively static data (e.g., a list of the &#8220;most recent&#8221; things), or is an action method whose output is constant for a given set of parameters (e.g, a dynamically-built navigation menu that highlights the visitor&#8217;s current location, where the current location is one of the parameters passed to the action method), and you don&#8217;t want to recompute it on every page hit. </p>
<p>Support for partial caching is a major advantage of PartialRequest over the use of viewdata-populating filters and partial views to render widgets. The filter/partialview technique can never support proper output caching, because inherently it mixes the widget&#8217;s viewdata with the main page&#8217;s viewdata, and the two can&#8217;t be distinguished by the time you&#8217;re actually rendering the view. The closest you could get would be to limit yourself to data caching, but that&#8217;s more complex and not always viable anyway, such as if you&#8217;re using an IQueryable to defer a SQL query until view rendering time. </p>
<h4>Notes</h4>
<p>To keep the [ActionOutputCache] code short and easy to understand, and because its current behaviour is adequate for my own current project&#8217;s needs, there are a number of limitations and caveats you should know about: </p>
<ul>
<li>It uses reflection to access HttpResponse&#8217;s private SwitchWriter() method. That&#8217;s how it&#8217;s able to intercept all the output piped to Response during subsequent filters and the action method being cached. It&#8217;s unfortunate that SwitchWriter() is marked private, but it is. If you don&#8217;t want to bypass the &#8220;private&#8221; access modifier this way, or if you can&#8217;t (e.g., because you&#8217;re not hosting in full-trust mode), then you can <a href="http://blog.codeville.net/blogfiles/2008/October/ActionOutputCacheAttribute.cs" target="_blank">download an alternative implementation that uses a filter</a> to capture output instead. This isn&#8217;t quite as straightforward, but some people will prefer/need it.
<li>It&#8217;s hard-coded to generate cache keys that vary by all incoming action method parameters and route values, and not by anything else. You would have to modify the code if you needed the ability to vary cache entry by other context parameters (such as unrelated querystring or form values).
<li>When generating cache keys, it assumes that the action method parameter types and route value types all have sensible implementations of GetHashCode(). This is fine for primitive types (strings, ints, etc.), but if you try to use it with a custom parameter types that have no proper implementation of GetHashCode(), it will pick a different cache key every time and appear not to be caching. So implement GetHashCode() properly on any such custom parameter types.
<li>It doesn&#8217;t attempt to cache and replay HTTP headers, so it&#8217;s not suitable for caching action methods that issue redirections.</li>
</ul>
<p>In other words, it works great for most straightforward widget output caching scenarios, but if you&#8217;re doing something more complex then please be prepared to dive into the code yourself! Hope this is useful to a few people.</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=aCiEm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=aCiEm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=1OcQM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=1OcQM" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=EWWbm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=EWWbm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=BCjAM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=BCjAM" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/421857581" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/10/15/partial-output-caching-in-aspnet-mvc/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/10/15/partial-output-caching-in-aspnet-mvc/</feedburner:origLink></item>
		<item>
		<title>Partial Requests in ASP.NET MVC</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/420420854/</link>
		<comments>http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/#comments</comments>
		<pubDate>Tue, 14 Oct 2008 10:36:29 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/</guid>
		<description><![CDATA[In your ASP.NET MVC application, it can be tricky to combine multiple independent &#8220;widgets&#8221; on the same page. That&#8217;s because a WebForms-style hierarchy of independent controls clashes awkwardly against a purist&#8217;s one-way MVC pipeline. Widgets? I&#8217;m taking about that drill-down navigation widget you want in your sidebar, or the &#8220;most recent forum posts&#8221; widget you&#8217;d [...]]]></description>
			<content:encoded><![CDATA[<p>In your ASP.NET MVC application, it can be tricky to combine multiple independent &#8220;widgets&#8221; on the same page. That&#8217;s because a WebForms-style hierarchy of independent controls clashes awkwardly against a purist&#8217;s one-way MVC pipeline. Widgets? I&#8217;m taking about that drill-down navigation widget you want in your sidebar, or the &#8220;most recent forum posts&#8221; widget you&#8217;d put in the page footer. Things that need to fetch their own data independently of the page that hosts them.</p>
<p>So, you&#8217;ve got basically two options:</p>
<ol>
<li>Make sure each action prepares an absolutely complete set of ViewData for not just the main page you&#8217;re rendering but also for every widget it hosts. Then in your view you can render widgets by calling &lt;% Html.RenderPartial(&#8230;) %&gt;, passing to the partial view template the subset of ViewData needed to render that widget.</li>
<li>Allow actions or views to invoke other actions, spinning off multiple internal mini-MVC pipelines that prepare and render each widget. </li>
</ol>
<p>Incidentally, this is exactly the same choice on offer to Ruby on Rails developers, who face the exact same issue. However, in Rails-world, option 2 is frowned upon because of the framework&#8217;s performance issues. But we don&#8217;t need to have that problem in ASP.NET MVC.</p>
<p>These two options are both perfectly usable in ASP.NET MVC, and each has its strengths and is suited to different circumstances. </p>
<p><strong>Option 1</strong> keeps your MVC pipeline simple and elegant, but it struggles to scale up in complexity if you have many widgets or hierarchies of widgets that appear or disappear at different times. It&#8217;s nice to use filter attributes to inject the ViewData elements needed for each widget, but not nice if there are many. </p>
<p><strong>Option 2</strong> is conceptually much simpler and enables simpler code, though at runtime there are more moving parts. It&#8217;s more like having a collection of genuinely independent widgets.&nbsp; This is what you get with &lt;%= Html.RenderAction(&#8230;) %&gt; (which is sadly relegated to the MVC Futures assembly and has been left with some technical problems), and also with MvcContrib&#8217;s new idea of <em><a href="http://mhinze.com/subcontrollers-in-aspnet-mvc/" target="_blank">subcontrollers</a></em>.</p>
<p>You&#8217;re free to choose the option that works best for you in any individual case. If someone tells you that internal subrequests (option 2) are bad because it &#8220;isn&#8217;t MVC&#8221;, then just bite them on the face immediately. Also ask them why they&#8217;re still willing to use Ajax, and even &lt;IMG&gt; tags for that matter, given that both are a form of subrequest.</p>
<h4>About subcontrollers</h4>
<p>Firstly, thankyou to the <a href="http://www.mvccontrib.org/" target="_blank">MVC Contrib</a> guys, because the subcontrollers idea is neat and genuinely improves on what we had before with Html.RenderAction(). </p>
<p>The core idea of subcontrollers is putting into ViewData a delegate for each widget. The view can render the widget by invoking the delegate. This allows the view to be totally ignorant of the widget it&#8217;s rendering, leaving the controller in full control. That eliminates the main problem people had with Html.RenderAction(). Brilliant!</p>
<p>What I don&#8217;t like so much about MVC Contrib&#8217;s subcontrollers is that it&#8217;s quite a heavyweight and complex solution. Firstly you have to be using MVC Contrib, and then you have to learn a non-obvious set of new conventions, and an alternative controller base class, and do something funny with your default model binder. I think it&#8217;s possible to get virtually all the same benefits (and some extra ones) with a utility class that&#8217;s just 17 lines long. </p>
<h4>Partial Requests are easy</h4>
<p>You&#8217;ve heard of partial views, so how about <em>partial requests</em>? Within any MVC request, you can set up a collection of internal partial requests, each of which can set up its own internal partial requests and so on. Each partial request renders a plain old action method in any of your plain regular controllers, and each can produce an independent widget. I&#8217;m calling them partial &#8220;requests&#8221; rather than &#8220;controllers&#8221; because they run a proper MVC request-handling pipeline that&#8217;s compatible with your routing system and your controller factory. Still, as with subcontrollers, all the control remains in controllers, and the view can be ignorant.</p>
<p>Drop this class somewhere in your MVC project:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> PartialRequest 
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> RouteValueDictionary RouteValues <span style="color: #000000;">&#123;</span> get; <span style="color: #0000FF;">private</span> set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> PartialRequest<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">object</span> routeValues<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        RouteValues = <span style="color: #0000FF;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span>routeValues<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Invoke<span style="color: #000000;">&#40;</span>ControllerContext context<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        RouteData rd = <span style="color: #0000FF;">new</span> RouteData<span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">Route</span>, context.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">RouteHandler</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> pair <span style="color: #0000FF;">in</span> RouteValues<span style="color: #000000;">&#41;</span>
            rd.<span style="color: #0000FF;">Values</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>pair.<span style="color: #0000FF;">Key</span>, pair.<span style="color: #0000FF;">Value</span><span style="color: #000000;">&#41;</span>;
        IHttpHandler handler = <span style="color: #0000FF;">new</span> MvcHandler<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> RequestContext<span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">HttpContext</span>, rd<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
        handler.<span style="color: #0000FF;">ProcessRequest</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">Current</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, when you want to attach a widget to your output, you can put a partial request into view data as so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;latestPosts&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #0000FF;">new</span> PartialRequest<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> 
    controller = <span style="color: #A31515;">&quot;Blog&quot;</span>, 
    action = <span style="color: #A31515;">&quot;LatestPosts&quot;</span> 
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>&#8230; then wherever you want to display that widget in your view, put:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;% <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>PartialRequest<span style="color: #000000;">&#41;</span>ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;partialAction&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>ViewContext<span style="color: #000000;">&#41;</span>; %&gt;</pre></div></div>

<p>&#8230; or if you prefer, use this trivial Html.RenderPartialRequest() helper:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> <span style="color: #0000FF;">class</span> PartialRequestsExtensions
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> <span style="color: #0000FF;">void</span> RenderPartialRequest<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span> HtmlHelper html, <span style="color: #0000FF;">string</span> viewDataKey<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        PartialRequest partial = html.<span style="color: #0000FF;">ViewContext</span>.<span style="color: #0000FF;">ViewData</span>.<span style="color: #0000FF;">Eval</span><span style="color: #000000;">&#40;</span>viewDataKey<span style="color: #000000;">&#41;</span> <span style="color: #0000FF;">as</span> PartialRequest;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>partial != <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
            partial.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>html.<span style="color: #0000FF;">ViewContext</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, having imported the relevant namespace, your view can simply contain:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;% Html.<span style="color: #0000FF;">RenderPartialRequest</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;latestPosts&quot;</span><span style="color: #000000;">&#41;</span>; %&gt;</pre></div></div>

<p>Assuming you have a regular BlogController with an action called LatestPosts, which might render its own view (have it render an MVC View User Control rather than an entire MVC View Page) or might simply return a ContentResult, you&#8217;ll find that its output is injected at the appropriate point in your view.</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/10/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="389" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/10/image-thumb.png" width="626" border="0"></a> </p>
<p>Of course, this works seamlessly with whatever arrangement of controller factories, model binders, and action invokers you might be using, and it executes any filters that surround the partial request&#8217;s target action method. </p>
<p>It&#8217;s testable, too: your unit tests can pick the PartialRequest object out of ViewData, and inspect its RouteValues collection, so check it&#8217;s invoking the expected target.</p>
<p>It naturally supports hierarchies of widgets, too: the action that a PartialRequest calls can fill its own independent ViewData collection with other PartialRequest objects, and invoke them from its own view, and so on.</p>
<p>It works well with Ajax, too: since your widget is the output of a plain old action method, you could use an Ajax request to re-fetch the widget&#8217;s contents and update it in the DOM without a full page refresh.</p>
<p>There&#8217;s one other major benefit, too, but I&#8217;m going to save that until tomorrow, because it&#8217;s cool enough to warrant a follow-up post in its own right&#8230;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.codeville.net%2f2008%2f10%2f14%2fpartial-requests-in-aspnet-mvc%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.codeville.net%2f2008%2f10%2f14%2fpartial-requests-in-aspnet-mvc%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=RZo3m"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=RZo3m" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=si9qM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=si9qM" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=S8xDm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=S8xDm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=b2ZDM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=b2ZDM" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/420420854" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/</feedburner:origLink></item>
		<item>
		<title>Short talk on "Writing about ASP.NET MVC" at Bristol .NET Developer Network, 16th October</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/409104585/</link>
		<comments>http://blog.codeville.net/2008/10/02/short-talk-on-writing-about-aspnet-mvc-at-bristol-net-developer-network-16th-october/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 09:50:02 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Speaking]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/10/02/short-talk-on-writing-about-aspnet-mvc-at-bristol-net-developer-network-16th-october/</guid>
		<description><![CDATA[If you&#8217;re in the Bristol (UK) area, you may be interested in the following event:
What: &#8220;Writing about ASP.NET MVC&#8220;Where: UWE (University of the West of England), Frenchay, Bristol (see FAQ for directions and a map) - Room 2q50 (in Q block)When: Thursday 16th October 2008, 6:30pm (Doors open 6:00pm)How to sign up
I&#8217;ll be talking about [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re in the Bristol (UK) area, you may be interested in the following event:</p>
<p style="border-right: black 1px solid; padding-right: 8px; border-top: black 1px solid; padding-left: 8px; background: #ddf; padding-bottom: 8px; margin: 0px 8px 8px; border-left: black 1px solid; width: 80%; padding-top: 8px; border-bottom: black 1px solid" align="left"><strong>What</strong>: &#8220;<em>Writing about ASP.NET MVC</em>&#8220;<br /><strong>Where</strong>: UWE (University of the West of England), Frenchay, Bristol (see <a href="http://www.dotnetdevnet.com/Default.aspx?tabid=53"><b>FAQ</b></a> for directions and a map) - Room 2q50 (in Q block)<br /><strong>When:</strong> Thursday 16th October 2008, 6:30pm (Doors open 6:00pm)<br /><a href="http://www.dotnetdevnet.com/Meetings/tabid/54/EntryID/24/Default.aspx" target="_blank">How to sign up</a></p>
<p>I&#8217;ll be talking about the <a href="http://www.amazon.com/Pro-ASP-NET-MVC-Framework/dp/1430210079" target="_blank">ASP.NET MVC book</a> I&#8217;m writing at the moment, but perhaps more interestingly, about the whole subject of writing a software book.</p>
<ul>
<li>Who can write a software book?
<li>How do you get a contract with a major publisher?
<li>How good is the money? What other benefits do you get?
<li>How much time and effort does it take? How does the editing process work?
<li>Is it for you?</li>
</ul>
<p>It will be a <u>short</u> talk, because the main event that evening is <a href="http://geekswithblogs.net/twickers/Default.aspx" target="_blank">Liam Westley</a>&#8217;s talk, entitled <em>Virtualisation for developers - What, Why, Where?</em>.</p>
<p>With apologies to Oren Eini, <a href="http://ayende.com/Blog/archive/2008/10/01/speaking-at-.net-developer-network.aspx" target="_blank">whose talks at the same venue earlier in the same week</a> are now unlikely to get many - if any - attendees, because of the massive enthusiasm and anticipation for mine and Liam&#8217;s blockbuster performances. <img src='http://blog.codeville.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=CFZCm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=CFZCm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=RNVrM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=RNVrM" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=1N1lm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=1N1lm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=8FWkM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=8FWkM" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/409104585" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/10/02/short-talk-on-writing-about-aspnet-mvc-at-bristol-net-developer-network-16th-october/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/10/02/short-talk-on-writing-about-aspnet-mvc-at-bristol-net-developer-network-16th-october/</feedburner:origLink></item>
		<item>
		<title>Thoughts on validation in ASP.NET MVC applications</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/386956770/</link>
		<comments>http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 19:19:32 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/</guid>
		<description><![CDATA[A couple of months back, I supplied some code for doing model-based validation in an ASP.NET MVC application in a way that automatically generates client-side validation JavaScript. That was pretty popular. Lots of people are enthusiastic about expressing validation rules as attributes on model properties. However, ASP.NET MVC has been enhanced since then, and so [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of months back, I supplied some code for doing <a href="http://blog.codeville.net/?p=86" target="_blank">model-based validation in an ASP.NET MVC application</a> in a way that automatically generates client-side validation JavaScript. That was pretty popular. Lots of people are enthusiastic about expressing validation rules as attributes on model properties. However, ASP.NET MVC has been enhanced since then, and so have my views on what constitutes tidy and effective validation. </p>
<p>So, let&#8217;s start with the new technology. MVC Preview 5 comes with two new API pieces that seem relevant to validation:</p>
<ul>
<li><strong>ModelState</strong>. Controllers now have an official way to pass validation error information to views. Populate ViewData.ModelState, then you can use the built-in HTML helpers to render error message summaries, and to highlight input fields that correspond to errors.</li>
<li><strong>Model binders</strong>. Controllers are expected to populate model objects from form posts using the IModelBinder API. You can create custom binders - the framework calls your binder to obtain a value for each model property. (If you don&#8217;t understand this, don&#8217;t worry - it turns out not to be relevant.)</li>
</ul>
<p>The obvious thing to do (and I&#8217;ve seen several forum posts and blog comments suggest this) is to make a custom model binder that applies validation rules (maybe ones expressed as attributes on model properties, such as [IsRequired]) and populates ModelState with any errors it finds. However, there are technical issues that make such a design unworkable in Preview 5 (model binders don&#8217;t get told what type of model object they&#8217;re providing values for). And more importantly than the current technical issues, that sort of design would be <em>totally undesirable</em> anyway. Validation has nothing to do with controllers binding form posts to model objects, as I&#8217;ll explain.</p>
<p>In the last week, <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx" target="_blank">Scott Guthrie posted</a> about handling form posting/validation scenarios in ASP.NET MVC, and <a href="http://weblogs.asp.net/stephenwalther/archive/2008/09/08/asp-net-mvc-application-building-forums-4-server-side-form-validation.aspx" target="_blank">so did Stephen Walther</a>. The following design has some things in common with each of their designs, but some important differences too.</p>
<h4>Basic principles</h4>
<p>So, how do you design a pattern for validation? Like any design, start by deciding what characteristics are really important to you, and build from there. Here&#8217;s what I consider to be important truths of validation:</p>
<ol>
<li>Model objects should perform <em>and </em>enforce validation at the appropriate time.</li>
<li>Validation rules should be expressible in plain old C#.</li>
<li>Validation rules and business rules are at opposite ends of the <em>same </em>spectrum.</li>
<li>Errors should bubble up to the UI automatically (no code needed).</li>
<li>Client-side validation is optional - it&#8217;s purely for convenience.</li>
</ol>
<h4>And what does that mean?</h4>
<p>[1] says that model objects don&#8217;t merely <em>hold</em> validation rules (e.g., as attributes on their properties), but model objects also <em>actually enforce</em> those rules. So, <strong>it&#8217;s not acceptable for a controller class to make the decision to validate </strong>(as they do in many other examples) - that would undermine the model&#8217;s encapsulation, and would mean that a badly-behaved controller could choose to skip validation. It&#8217;s the <em>model</em> that enforces validation, and it does so at a time of its own choosing - usually when something is being committed (e.g., when the model object is being saved to the database), but it might also choose to validate simple property formatting rules during property setters.</p>
<p>Now, if the model is capable of enforcing validation at a time of its own choosing, then it needs a general-purpose mechanism to forcibly abort certain controller operations when validation rules are violated. Fortunately, C# comes with the perfect mechanism: exceptions. There&#8217;s nothing clever about this (simplicity is the goal) - when the model decides it won&#8217;t allow an operation, it throws an exception. The operation is forcibly aborted. The controller must obey.</p>
<p>Also, bear in mind that certain validation rules can only be enforced at the point of committing data or finalizing actions. For example, &#8220;usernames must be unique&#8221; will probably be enforced in your database (with a UNIQUE constraint). You therefore can&#8217;t rely on a single &#8220;validation&#8221; moment - the model has to be free to issue rule exceptions at any point during its processing, and the controller shouldn&#8217;t need any special-case logic to deal with this. This requirement fits quite easily into the following design.</p>
<p>[2] just says that I don&#8217;t want to rely on any kind of rules engine. Now I&#8217;m perfectly happy to have reusable attributes to represent certain simple property formatting rules (e.g., [IsRequired], [DataFormat(Formats.EmailAddress)]), and you could even build a custom rules engine, but these are built on the fact that arbitrary C# is allowed.</p>
<p>[3] tries to clarify that simple property formatting rules (e.g., must be valid SSN) are a good start, but not adequate on their own. Certain business rules describe whether or not an operation is allowed (e.g., usernames must be unique), might relate to interactions of multiple properties, might involve arbitrarily complex logic, and these ought to fit into the validation framework too. See the diagram below.</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/09/image-thumb2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="199" alt="image_thumb2" src="http://blog.codeville.net/wp-content/uploads/2008/09/image-thumb2-thumb.png" width="585" border="0"></a></p>
<p>[4] is about making the system easy to maintain. When I add a new validation rule to my model, I want all controllers/views that work on that model type to render suitable error messages automatically, without changing any controller/view code.</p>
<p>Now, remember that when the model decides some rule has been violated, it throws an exception. If that exception is of some special type (let&#8217;s call it BusinessRuleException), then that exception can describe in some strongly-typed way which rule was validated and how. In fact, it can describe multiple rule validations simultaneously. All we need now is for controllers to catch BusinessRuleExceptions, use them to populate ViewData.ModelState, then ASP.NET MVC&#8217;s built-in helpers will take care of displaying the messages. We can do localization in this step too, for multilingual error messages.</p>
<p>[5] says that it&#8217;s nice to have a helper to generate client-side validation code automatically, but the helper doesn&#8217;t have to replicate <em>every</em> rule on the client. Obviously, since we&#8217;re allowing arbitrary C# rules, there&#8217;s no automatic translation of arbitrary rules to JavaScript. Sometimes client-side validation is impossible anyway (e.g., &#8220;usernames must be unique&#8221;). However, if some simple property formatting rules are implemented as attributes (e.g., [IsRequired]), then we can generate client-side code from these attributes. It won&#8217;t cover all rules, but it will cover many of them, and that&#8217;s good enough.</p>
<h4>Time for some code plz</h4>
<p>Yes I know - reading English <em>is </em>hard work. Far easier if I show you some C# code. Here&#8217;s how a model class might look:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> Person
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>Required<span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#91;</span>StringLength<span style="color: #000000;">&#40;</span><span style="color: #000000;">20</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span> 
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Name <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>Required<span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#91;</span>Range<span style="color: #000000;">&#40;</span><span style="color: #000000;">1</span>, <span style="color: #000000;">200</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span> 
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">int</span>? Age <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> EnsureValid<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">// If any of this object's property values conflicts with a validation [Attribute],</span>
        <span style="color: #008000;">// it will add an entry to the violations collection</span>
        RuleViolations violations = ValidationHelpers.<span style="color: #0000FF;">RunValidationAttributes</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #008000;">// Now we can run any other custom C# validation logic</span>
        <span style="color: #0000FF;">if</span><span style="color: #000000;">&#40;</span>Age.<span style="color: #0000FF;">HasValue</span> &amp;&amp; <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">Year</span> - Age.<span style="color: #0000FF;">Value</span><span style="color: #000000;">&#41;</span> % <span style="color: #000000;">4</span> == <span style="color: #000000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            violations.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> ArbitraryViolation<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Age&quot;</span>, <span style="color: #A31515;">&quot;Sorry, you were probably born on a leap year, so we won't let you register.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>!violations.<span style="color: #0000FF;">IsEmpty</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0000FF;">throw</span> <span style="color: #0000FF;">new</span> BusinessRuleException<span style="color: #000000;">&#40;</span>violations<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> <span style="color: #0000FF;">class</span> PersonRepository
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> <span style="color: #0000FF;">void</span> SavePerson<span style="color: #000000;">&#40;</span>Person person<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">// The model is reponsible for deciding when to validation.</span>
        <span style="color: #008000;">// It chooses to validate now. If there's a violation, it will</span>
        <span style="color: #008000;">// throw an exception</span>
        person.<span style="color: #0000FF;">EnsureValid</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #008000;">// Good - it was valid. Todo: now save to database</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>As you can see, there are some simple property format rules implemented using attributes (these are the standard ones shipped in System.ComponentModel.DataAnnotations), but these are just a special case. You can of course use arbitrary C# logic when enforcing validation.</p>
<p>I don&#8217;t need to have a special method marked as <em>the</em> validation method (or an IValidatable interface or anything like that), because the model layer makes its own decision when to validate, and chooses how to do that. It just has to throw a BusinessRuleException if there&#8217;s a problem. In this example, it chooses to enforce validation before writing to the database, but you could choose to validate certain properties during their setter methods if you wanted.</p>
<p>Next, how does a controller look? It follows a general pattern like the following. The critical bit is that model operations are wrapped in a try&#8230;catch so that it can recover from errors and display suitable UI feedback.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> RegistrationController : Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;GET&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> ViewResult Edit<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;POST&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> ActionResult Edit<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> unused<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Person model = <span style="color: #0000FF;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">try</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>!TryUpdateModel<span style="color: #000000;">&#40;</span>model, <span style="color: #0000FF;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #A31515;">&quot;Name&quot;</span>, <span style="color: #A31515;">&quot;Age&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">// At some point it may be possible to have a custom binder that throws a BusinessRuleException if there were setter exceptions, but as of Preview 5, have to use the slightly hacky TryUpdateModel()</span>
                <span style="color: #0000FF;">throw</span> <span style="color: #0000FF;">new</span> BusinessRuleException<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008000;">// The real validation happens to be enforced by the model here, but that's no concern for the controller</span>
            PersonRepository.<span style="color: #0000FF;">SavePerson</span><span style="color: #000000;">&#40;</span>model<span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008000;">// The operation completed successfully (so validation must have passed)</span>
            <span style="color: #0000FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Completed&quot;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0000FF;">catch</span> <span style="color: #000000;">&#40;</span>BusinessRuleException ex<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008000;">// Generate suitable localized UI feedback based on exception that was thrown</span>
            ex.<span style="color: #0000FF;">AddToModelState</span><span style="color: #000000;">&#40;</span>ViewData.<span style="color: #0000FF;">ModelState</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008000;">// Re-render edit screen</span>
            <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span>model<span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Notice the call to ex.AddToModelState(ViewData.ModelState);. I&#8217;ve implemented that as an extension method on BusinessRuleException (so as not to mix ASP.NET MVC concerns with the core BusinessRuleException class) - it simply iterates through the list of RuleViolations objects, and generates/adds some localized UI feedback to ViewData.ModelState for each violation. </p>
<p>I haven&#8217;t included the full source code here because it&#8217;s still all a bit proof-of-concept, but it&#8217;s not too hard to fill in the gaps and get a working implementation.</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/09/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="287" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/09/image-thumb.png" width="570" border="0"></a> </p>
<h4>And what of client-side validation?</h4>
<p>As we discussed earlier, not all rules can be translated to client-side validation code. However, since some of the simpler rules (those on the green end of the validation-businessrule spectrum) are often implemented as System.ComponentModel.DataAnnotations attributes, it would be a straightforward job to make a Html.ClientSideValidation(object model) helper that dynamically generates suitable validation JavaScript. This bit is essentially the same as what I implemented in my <a href="http://blog.codeville.net/?p=86" target="_blank">previous MVC validation post</a>.</p>
<p>Of course, you could have a pluggable system to generate a JS validation configuration suitable for multiple client-side validation frameworks. </p>
<h4>About setter exceptions</h4>
<p>As mentioned earlier, sometimes it&#8217;s desirable to enforce validation rules in property setters. This gives you solid assurance that your model object can&#8217;t have invalid property values, because when *any* code (an MVC controller or model binder, or some other domain or service code) tries to manipulate the model object, they&#8217;ll never get away with setting invalid property values. This strategy applies only to simple individual property formatting rules (the green end of the spectrum). </p>
<p>When setters throw exceptions, MVC Preview 5&#8217;s DefaultModelBinder is clever enough to capture them one property at a time, building up a ModelState structure. Unfortunately, at present, it disregards the exception type, so you can&#8217;t use it to generate suitable UI feedback later. I&#8217;ve <a href="http://www.codeplex.com/aspnet/WorkItem/View.aspx?WorkItemId=2255" target="_blank">asked for this to be fixed</a> - let&#8217;s be optimistic that the MVC team will give tighter support for setter exceptions in the next update.</p>
<p>Now, here&#8217;s an interesting twist. If we want some validation rules to be enforced in setters, and those rules are expressed as [Attributes], then wouldn&#8217;t it be cool if that logic was automatically injected into the setter by the attribute? This gets us into aspect-oriented programming territory (AOP). Unfortunately the .NET CLR doesn&#8217;t have much support for AOP. <a href="http://www.postsharp.org/" target="_blank">PostSharp</a> is the best option we&#8217;ve got, but it does require a special code compilation process.</p>
<p>If instead of using the System.ComponentModel.DataAnnotations attributes we used custom attributes, then they could implement PostSharp&#8217;s special interfaces. Then, when you compile with PostSharp, the attribute&#8217;s simple validation logic can automatically get injected into the property setter. However, if you <em>don&#8217;t </em>compile with PostSharp, then the logic wouldn&#8217;t automatically get injected into the setter, and you&#8217;d cleanly fall back on the behavior I showed earlier in this post.</p>
<p>Of course, this would only be useful if ASP.NET MVC gets better support for setter exceptions.</p>
<h4>So, would <strong><u>you</u></strong> do validation like this?</h4>
<p>Long post&#8230; sorry! Dear readers, I&#8217;d be very pleased to hear of any feedback on this design. If there&#8217;s any consensus on how it should work, then I or someone else could work it up into a downloadable reusable set of components and classes. This would include:</p>
<ul>
<li>The BusinessRuleException class that you can throw from your model layer to signal and describe arbitrary invalid user actions. It would hold a set of strongly-typed RuleViolation classes (e.g., RequiredFieldViolation, StringLengthViolation) that your controller or view can use to generate localized UI feedback</li>
<li>Support for running System.ComponentModel.DataAnnotations attributes against a model object, to produce a collection of RuleViolation objects if there were problems</li>
<li>A custom model binder that knows how to generate and throw a suitable BusinessRuleException if there were setter exceptions</li>
<li>A helper for generating client-side validation code based on System.ComponentModel.DataAnnotations attributes (perhaps supporting multiple JS validation libraries)</li>
</ul>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=890cm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=890cm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=lABKM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=lABKM" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=aK8bm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=aK8bm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=ORK6M"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=ORK6M" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/386956770" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/</feedburner:origLink></item>
		<item>
		<title>Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/380651968/</link>
		<comments>http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/#comments</comments>
		<pubDate>Mon, 01 Sep 2008 17:37:33 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/</guid>
		<description><![CDATA[Cross-site scripting (XSS) is widely regarded as the number one security issue on the web. But since XSS gets all the limelight, few developers pay much attention to another form of attack that&#8217;s equally destructive and potentially far easier to exploit. Your application can be vulnerable to cross-site request forgery (CSRF) attacks not because you [...]]]></description>
			<content:encoded><![CDATA[<p>Cross-site scripting (XSS) is <a href="http://www.owasp.org/index.php/Top_10_2007" target="_blank">widely</a> <a href="http://tinyurl.com/3q9j7w" target="_blank">regarded</a> as the number one security issue on the web. But since XSS gets all the limelight, few developers pay much attention to another form of attack that&#8217;s equally destructive and potentially far easier to exploit. Your application can be vulnerable to cross-site request forgery (CSRF) attacks not because you the developer did something wrong (as in, failing to encode outputs leads to XSS), but simply because of how the whole Web is designed to work. Scary!</p>
<h4>How CSRF works</h4>
<p>So, what&#8217;s it all about? All web application platforms are potentially vulnerable to CSRF, but in this post I&#8217;ll focus on ASP.NET MVC. Imagine you have a controller class as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> UserProfileController : Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> ViewResult Edit<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0000FF;">public</span> ViewResult SubmitUpdate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">// Get the user's existing profile data (implementation omitted)</span>
        ProfileData profile = GetLoggedInUserProfile<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #008000;">// Update the user object</span>
        profile.<span style="color: #0000FF;">EmailAddress</span> = Request.<span style="color: #0000FF;">Form</span><span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;email&quot;</span><span style="color: #000000;">&#93;</span>;
        profile.<span style="color: #0000FF;">FavoriteHobby</span> = Request.<span style="color: #0000FF;">Form</span><span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;hobby&quot;</span><span style="color: #000000;">&#93;</span>;
        SaveUserProfile<span style="color: #000000;">&#40;</span>profile<span style="color: #000000;">&#41;</span>;
&nbsp;
        TempData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;message&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #A31515;">&quot;Your profile was updated.&quot;</span>;
        <span style="color: #0000FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This is all very normal. First, the visitor goes to <strong>Edit()</strong>, which renders some form to let them change their user profile details. Secondly, they post that form to <strong>SubmitUpdate()</strong>, which saves the changes to their profile record in the database. There&#8217;s no XSS vulnerability here. Everything&#8217;s fine, right? We implement this sort of thing all the time&#8230;</p>
<p>Unfortunately, this innocent controller is an easy target for CSRF. Imagine that an attacker sets up the following HTML page and hosts it on some server of their own:</p>

<div class="wp_syntax"><div class="code"><pre>&lt;body onload=&quot;document.getElementById('fm1').submit()&quot;&gt;
    &lt;form id=&quot;fm1&quot; action=&quot;http://yoursite/UserProfile/SubmitUpdate&quot; method=&quot;post&quot;&gt;
        &lt;input name=&quot;email&quot; value=&quot;hacker@somewhere.evil&quot; /&gt;
        &lt;input name=&quot;hobby&quot; value=&quot;Defacing websites&quot; /&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre></div></div>

<p>Next, they somehow persuade a victim to visit this page (basic social engineering, look it up). When this HTML page loads, it submits a valid form post to <strong>/UserProfile/SubmitUpdate</strong> on <em>your server</em>. </p>
<p>Assuming you&#8217;re using Windows authentication or some kind of cookie-based authentication system such as Forms Authentication, the automated form post will be processed within the victim&#8217;s established authentication context, and will successfully update the victim&#8217;s email address to something under the attacker&#8217;s control. All the attacker has to do now is use your &#8220;forgotten password&#8221; facility, and they&#8217;re taken control of the victim&#8217;s account.</p>
<p>Of course, instead of changing an victim&#8217;s email address, they can perform any action that the victim can perform with a single POST request. For example, they might be able to grant administrative permissions to another account, or post something defamatory to a CMS.</p>
<h4>Ways to stop CSRF</h4>
<p>There are two main ways to block CSRF:</p>
<ul>
<li>Check that incoming requests have a <strong>Referer</strong> header referencing your domain. This will stop requests unwittingly submitted from a third-party domain. However, some people disable their browser&#8217;s <strong>Referer</strong> header for privacy reasons, and attackers can sometimes spoof that header if the victim has certain versions of Adobe Flash installed. This is a weak solution.</li>
<li>Put a user-specific token as a hidden field in legitimate forms, and check that the right value was submitted. If, for example, this token is the user&#8217;s password, then a third-party can&#8217;t forge a valid form post, because they don&#8217;t know each user&#8217;s password. However, don&#8217;t expose the user&#8217;s password this way: Instead, it&#8217;s better to use some random value (such as a GUID) which you&#8217;ve stored in the visitor&#8217;s Session collection or into a Cookie.</li>
</ul>
<h4>Using the AntiForgeryToken helpers</h4>
<p>With Preview 5, Microsoft has added a set of helpers to the &#8220;futures&#8221; assembly, Microsoft.Web.Mvc.dll, that give you a means to detect and block CSRF using the &#8220;user-specific tokens&#8221; technique. </p>
<p>To use these helpers to protect a particular form, put an Html.AntiForgeryToken() into the form, e.g.,</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;% <span style="color: #0000FF;">using</span><span style="color: #000000;">&#40;</span>Html.<span style="color: #0000FF;">Form</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;UserProfile&quot;</span>, <span style="color: #A31515;">&quot;SubmitUpdate&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> %&gt;
    &lt;%= Html.<span style="color: #0000FF;">AntiForgeryToken</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> %&gt;
    &lt;!-- rest of form goes here --&gt;
&lt;% <span style="color: #000000;">&#125;</span> %&gt;</pre></div></div>

<p>This will output something like the following:</p>

<div class="wp_syntax"><div class="code"><pre>&lt;form action=&quot;/UserProfile/SubmitUpdate&quot; method=&quot;post&quot;&gt;
    &lt;input name=&quot;__MVC_AntiForgeryToken&quot; type=&quot;hidden&quot; value=&quot;saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs&quot; /&gt;
    &lt;!-- rest of form goes here --&gt;
&lt;/form&gt;</pre></div></div>

<p>At the same time, Html.AntiForgeryToken() will give the visitor a cookie called __MVC_AntiForgeryToken, with the same value as the random hidden value shown above. </p>
<p>Next, to validate an incoming form post, add the [ValidateAntiForgeryToken] filter to your target action method. For example,</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>ValidateAntiForgeryToken<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> ViewResult SubmitUpdate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">// ... etc</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This is an authorization filter that checks that:</p>
<ul>
<li>The incoming request has a cookie called <strong>__MVC_AntiForgeryToken</strong></li>
<li>The incoming request has a Request.Form entry called <strong>__MVC_AntiForgeryToken</strong></li>
<li>These cookie and Request.Form values match</li>
</ul>
<p>Assuming all is well, the request goes through as normal. But if not, boom!, there&#8217;s an authorization failure with message &#8220;A required anti-forgery token was not supplied or was invalid&#8221;. </p>
<p>This prevents CSRF because even if a potential victim has an <strong>__MVC_AntiForgeryToken</strong> cookie, an attacker can&#8217;t find out its value, so they can&#8217;t forge a valid form post with the same value in Request.Form. But legitimate users aren&#8217;t inconvenienced at all; the mechanism is totally silent.</p>
<h4>Using salt</h4>
<p>Salt? What? In case you want to protect multiple forms in your application independently of each other, you can use a &#8220;salt&#8221; value when you call Html.AntiForgeryToken(), e.g., </p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;%= Html.<span style="color: #0000FF;">AntiForgeryToken</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;someArbitraryString&quot;</span><span style="color: #000000;">&#41;</span> %&gt;</pre></div></div>

<p>&#8230; and also in [ValidateAntiForgeryToken], e.g., </p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>ValidateAntiForgeryToken<span style="color: #000000;">&#40;</span>Salt=<span style="color: #A31515;">&quot;someArbitraryString&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> ViewResult SubmitUpdate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">// ... etc</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Salt is just an arbitrary string. A different salt value means a different anti-forgery token will be generated. This means that even if an attacker manages to get hold of a valid token somehow, they can&#8217;t reuse it in other parts of the application where a different salt value is required. (If anyone can suggest other use cases for salt, please let me know.)</p>
<h4>Limitations of the Anti-Forgery helpers</h4>
<p>ASP.NET MVC&#8217;s anti-CSRF helpers work very nicely, but you should be aware of a few limitations:</p>
<ul>
<li>All legitimate visitors must accept cookies (otherwise, [ValidateAntiForgeryToken] will deny their form posts). Arguably this isn&#8217;t a limitation, because unless visitors allow cookies, you probably don&#8217;t have anything to protect anyway.</li>
<li>It only works with POST requests, not GET requests. Arguably this isn&#8217;t a limitation, because under the normal HTTP conventions, you shouldn&#8217;t be using GET requests for anything other than read-only operations.</li>
<li>It&#8217;s easily bypassed if you have any XSS holes on your domain. An XSS hole would allow an attacker to read a victim&#8217;s anti-forgery token value, then use it to forge valid posts. So, don&#8217;t have XSS holes!</li>
<li>It relies on the potential victim&#8217;s browser implementing cross-domain boundaries solidly. Browsers are supposed to stop foreign domains from reading your app&#8217;s response text and cookies, and are supposed to stop foreign domains from writing cookies to your domain. If an attacker manages to find a way around this, they can bypass [ValidateAntiForgeryToken]. Of course that&#8217;s not supposed to be possible. For the most part, modern browsers block this line of attack.</li>
</ul>
<p>In conclusion, ASP.NET MVC&#8217;s anti-CSRF helpers are easy to use, and work very nicely thank you!</p>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=gCaJm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=gCaJm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=7gj9M"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=7gj9M" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=BZBpm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=BZBpm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=HX0KM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=HX0KM" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/380651968" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/</feedburner:origLink></item>
		<item>
		<title>Using the browser’s native login prompt</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/374175058/</link>
		<comments>http://blog.codeville.net/2008/08/25/using-the-browsers-native-login-prompt/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 10:48:49 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/08/25/using-the-browsers-native-login-prompt/</guid>
		<description><![CDATA[These days, every web site has its own unique &#8220;login&#8221; screen, along with its own separate system for remembering your login name and password. How many millions of developer-hours are spent designing and implementing these screens? And yet, every web browser has a built-in standard login prompt ready for you to use. For example:
  [...]]]></description>
			<content:encoded><![CDATA[<p>These days, every web site has its own unique &#8220;login&#8221; screen, along with its own separate system for remembering your login name and password. How many millions of developer-hours are spent designing and implementing these screens? And yet, every web browser has a built-in standard login prompt ready for you to use. For example:</p>
<p><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="225" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/08/image.png" width="244" border="0" valign="top"> <img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="105" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/08/image1.png" width="244" border="0" valign="top"> </p>
<p>These have been standard in web browsers since since 1558 AD, when the legendary Duke of Login first invented the idea of logging in. Respect!</p>
<p>Most web developers who want to do programmatic authentication (i.e., validating credentials against Forms Authentication or directly against a database) don&#8217;t use this native browser login prompt, for two reasons:</p>
<ul>
<li>It&#8217;s not clear how to make it work with programmatic authentication</li>
<li>It&#8217;s believed to be insecure (for some reason)</li>
</ul>
<p>First, I&#8217;ll show how to use the native login prompt programmatically with ASP.NET MVC, then we&#8217;ll talk about security.</p>
<h4>A Quick Overview of the HTTP Basic Authentication Protocol</h4>
<p>So, how does the native login prompt actually work? What makes it appear, and what data does it send from the browser to the server?</p>
<ol>
<li>The browser makes a request to some URL</li>
<li>The server sends back a response with an HTTP status code of 401 (meaning &#8220;Not authorized&#8221;), plus a header describing the types of authentication it will accept. For example:<br /><font face="Courier New" size="3">&nbsp;&nbsp;&nbsp; WWW-Authenticate: Basic</font></li>
<li>This makes the browser display a login prompt, but it doesn&#8217;t display any other text that&#8217;s in the response. (It only displays that response text if the user clicks &#8220;Cancel&#8221;.)</li>
<li>When the user enters some credentials, the browser resubmits the same request to the same URL, plus it also adds this extra header:<br /><font face="Courier New" size="3">&nbsp;&nbsp;&nbsp; Authorization: Basic <em>username:password</em></font><br />Note that the <em>username:password</em> bit is actually Base-64 encoded.</li>
<li>The server parses the username and password from the request, and decides whether the credentials are valid or not. If they are valid, it lets the user continue (so it might return a proper HTML response, or it might redirect to somewhere else). If they are invalid, it returns a 401 again (i.e., goes back to step 2).</li>
<li>If the user enters the same incorrect credentials twice in a row, the browser normally won&#8217;t bother resubmitting them and will just give up.</li>
</ol>
<h4>Using HTTP Basic Authentication programmatically in ASP.NET MVC</h4>
<p>Now you know how HTTP Basic authentication works, it&#8217;s easy to use it from ASP.NET MVC. Just follow the above script, playing the role of the server. </p>
<p>Let&#8217;s say you want to combine Forms Authentication with a browser-native login prompt. Start by setting up Forms Authentication, i.e., put into your web.config file:</p>

<div class="wp_syntax"><div class="code"><pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;authentication</span> <span style="color: #000066;">mode</span>=<span style="color: #ff0000;">&quot;Forms&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;forms</span> <span style="color: #000066;">loginUrl</span>=<span style="color: #ff0000;">&quot;~/Account/Login&quot;</span> <span style="color: #000066;">defaultUrl</span>=<span style="color: #ff0000;">&quot;~/&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;credentials</span> <span style="color: #000066;">passwordFormat</span>=<span style="color: #ff0000;">&quot;SHA1&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;user</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;admin&quot;</span> <span style="color: #000066;">password</span>=<span style="color: #ff0000;">&quot;e9fe51f94eadabf54dbf2fbbd57188b9abee436e&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/credentials<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/forms<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/authentication<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre></div></div>

<p>Note that e9fe51&#8230; is the SHA1 hash of &#8220;mysecret&#8221;, so this configuration has a single hard-coded login name, &#8220;admin&#8221;, with password &#8220;mysecret&#8221;. In a more realistic app you&#8217;d probably not have any &lt;credentials&gt; in your web.config, and instead set up a membership provider to store credentials in a database. But that doesn&#8217;t change the rest of this example.</p>
<p>Now, assuming you&#8217;ve decorated some controller or action method with <strong>[Authorize]</strong>, when the user visits that controller or action, they&#8217;ll be redirected to <strong>~/Account/Login</strong>. To handle that request, create a new controller class called <strong>AccountController</strong>, as follows. You can replace the default implementation of <strong>AccountController</strong> if you have one.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> AccountController : Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Login<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">// Ensure there's a return URL</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>Request.<span style="color: #0000FF;">QueryString</span><span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;ReturnUrl&quot;</span><span style="color: #000000;">&#93;</span> == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
            Response.<span style="color: #0000FF;">Redirect</span><span style="color: #000000;">&#40;</span>FormsAuthentication.<span style="color: #0000FF;">LoginUrl</span> + <span style="color: #A31515;">&quot;?ReturnUrl=&quot;</span> + Server.<span style="color: #0000FF;">UrlEncode</span><span style="color: #000000;">&#40;</span>FormsAuthentication.<span style="color: #0000FF;">DefaultUrl</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>TempData.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;allowLogin&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008000;">// See if they've supplied credentials</span>
            <span style="color: #0000FF;">string</span> authHeader = Request.<span style="color: #0000FF;">Headers</span><span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Authorization&quot;</span><span style="color: #000000;">&#93;</span>;
            <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>authHeader != <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span> &amp;&amp; <span style="color: #000000;">&#40;</span>authHeader.<span style="color: #0000FF;">StartsWith</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Basic&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008000;">// Parse username and password out of the HTTP headers</span>
                authHeader = authHeader.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Basic&quot;</span>.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Trim</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0000FF;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> authHeaderBytes = Convert.<span style="color: #0000FF;">FromBase64String</span><span style="color: #000000;">&#40;</span>authHeader<span style="color: #000000;">&#41;</span>;
                authHeader = Encoding.<span style="color: #0000FF;">UTF7</span>.<span style="color: #0000FF;">GetString</span><span style="color: #000000;">&#40;</span>authHeaderBytes<span style="color: #000000;">&#41;</span>;
                <span style="color: #0000FF;">string</span> userName = authHeader.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">':'</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">0</span><span style="color: #000000;">&#93;</span>;
                <span style="color: #0000FF;">string</span> password = authHeader.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">':'</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">1</span><span style="color: #000000;">&#93;</span>;
&nbsp;
                <span style="color: #008000;">// Validate login attempt</span>
                <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>FormsAuthentication.<span style="color: #0000FF;">Authenticate</span><span style="color: #000000;">&#40;</span>userName, password<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    FormsAuthentication.<span style="color: #0000FF;">RedirectFromLoginPage</span><span style="color: #000000;">&#40;</span>userName, <span style="color: #0000FF;">false</span><span style="color: #000000;">&#41;</span>;
                    <span style="color: #0000FF;">return</span>;
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">// Force the browser to pop up the login prompt</span>
        Response.<span style="color: #0000FF;">StatusCode</span> = <span style="color: #000000;">401</span>;
        Response.<span style="color: #0000FF;">AppendHeader</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;WWW-Authenticate&quot;</span>, <span style="color: #A31515;">&quot;Basic&quot;</span><span style="color: #000000;">&#41;</span>;
        TempData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;allowLogin&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #0000FF;">true</span>;
&nbsp;
        <span style="color: #008000;">// This gets shown if they click &quot;Cancel&quot; to the login prompt</span>
        Response.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;You must log in to access this URL.&quot;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<blockquote>
<p><em>(By the way, I&#8217;m fully aware that the Login() action eschews a number of ASP.NET MVC best practices - it doesn&#8217;t return a useful ActionResult, and it calls Response.Redirect() directly. This makes it unsuitable for unit testing. I did this because fundamentally it&#8217;s using the static and hard-to-test FormsAuthentication API anyway. You can wrap all the static method calls inside an interface and use constructor injection, and perhaps return some special HttpBasicActionResult, if you want to make it testable - but I didn&#8217;t want to distract from the real point of this example.)</em></p>
</blockquote>
<p>That does it! Now when a visitor goes to anything protected with <strong>[Authorize]</strong>, they&#8217;ll get a browser-native login prompt, such as the one shown below. If the visitor enters valid credentials (i.e., admin/mysecret), then they&#8217;ll be given a Forms Authentication cookie, and will be redirected back to the action method they requested.</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/08/image2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="435" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/08/image-thumb.png" width="805" border="0"></a> </p>
<p>Notice in this screenshot that IE gives a warning about &#8220;<em>basic authentication without a secure connection</em>&#8220;. We&#8217;ll talk about secure connections (SSL) in a moment.</p>
<p>Next, you&#8217;ll want to give visitors some way of logging out. This has nothing to do with HTTP basic authentication; it&#8217;s just a matter of revoking the visitor&#8217;s Forms Authentication cookie. So, add this to AccountController:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> RedirectResult Logout<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    FormsAuthentication.<span style="color: #0000FF;">SignOut</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #0000FF;">return</span> Redirect<span style="color: #000000;">&#40;</span>FormsAuthentication.<span style="color: #0000FF;">DefaultUrl</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>What a very simple way of getting a nice login UI. </p>
<h4>Is this secure?</h4>
<p>HTTP Basic authentication has an undeserved reputation for being insecure. Yes, it does send credentials over the wire in plain text (well, Base-64 encoded, but that&#8217;s basically the same). But then if you make a custom login form (such as the one in the default ASP.NET MVC project template), that sends credentials in plain text too. The level of security is identical.</p>
<p>Either way, you must protect the transmission by doing it over SSL. And that&#8217;s just as easy, or difficult, whether you use the browser&#8217;s native login prompt or create your own custom login screen.</p>
<p>One quirk of HTTP basic authentication is that the browser keeps on sending the <strong>Authorization</strong> header with <em>every</em> request that appears to be in the same folder as the one where it was originally requested. So, in this example, the browser will keep sending the <strong>Authorization</strong> header with every request to <strong>AccountController</strong> (but not to other controllers). That means you shouldn&#8217;t let the browser perform any requests to <strong>AccountController</strong> that aren&#8217;t wrapped in SSL. Also, HTTP basic authentication doesn&#8217;t give any natural way to log out, which is why I added the TempData[&#8221;allowLogin&#8221;] test so that you always get a login prompt the first time you go to <strong>Login()</strong>. When a visitor clicks &#8220;log out&#8221;, it does erase their Forms Authentication cookie, but the browser still has the credentials in its HTTP Basic cache. The user acts as logged out, but the credentials are still in the browser&#8217;s memory until they close the browser.</p>
<h4>Conclusion</h4>
<p>Using ASP.NET MVC, it&#8217;s easy to make a browser pop open its native login prompt, and to parse out the credentials that a user enters. These login credentials are no more or less secure than credentials entered into a normal custom login form.</p>
<p>However, it&#8217;s also easy to create a custom login form. This gives you more control over its appearance, and avoids the quirks of HTTP basic authentication with regard to logging out. Therefore, for most applications, it&#8217;s usually best still to create a custom login form.</p>
<blockquote>
<p><em>This article was expanded from a short example that I was originally going to put in my <a href="http://www.amazon.com/Pro-ASP-NET-MVC-Framework/dp/1430210079" target="_blank">forthcoming ASP.NET MVC book</a>, but I decided to remove it from the book because it isn&#8217;t quite worthy enough&#8230;</em></p>
</blockquote>
<div class="feedflare">
<a href="http://feeds.codeville.net/~f/SteveCodeville?a=pyk0m"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=pyk0m" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=uhjbM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=uhjbM" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=RciHm"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=RciHm" border="0"></img></a> <a href="http://feeds.codeville.net/~f/SteveCodeville?a=VJXvM"><img src="http://feeds.codeville.net/~f/SteveCodeville?i=VJXvM" border="0"></img></a>
</div><img src="http://feeds.codeville.net/~r/SteveCodeville/~4/374175058" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/08/25/using-the-browsers-native-login-prompt/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/08/25/using-the-browsers-native-login-prompt/</feedburner:origLink></item>
		<item>
		<title>Adding HTTPS/SSL support to ASP.NET MVC routing</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/356624368/</link>
		<comments>http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/#comments</comments>
		<pubDate>Tue, 05 Aug 2008 18:11:47 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Routing]]></category>

		<guid