SLaks.Blog

Making the world a better place, one line of code at a time

Dissecting Razor, part 1: Parts of the framework

Posted on Tuesday, February 01, 2011, at 3:51:00 AM UTC

Razor involves two distinct components: The Razor engine and the WebPages framework.

The Razor engine, in System.Web.Razor.dll, parses CSHTML (and VBHTML) files into CodeDOM trees.  Except for the word Web in project name, the engine has nothing to do with ASP.Net; it doesn’t even reference System.Web.dll.  In fact, it targets the .Net Client Profile, and only references mscorlib and System.dll.

The Razor engine is aware of all of Razor’s syntax-level features (code nuggets, sections, helpers), but is not aware of what they mean; it blindly transforms them into function calls.

The Razor engine can be used without ASP.Net for any kind of templating system.  This is done by inheriting the RazorEngineHost class to provide default code-generation settings (such as base class and method name), then passing the host to a RazorTemplateParser. 

The standard syntax will be annoying when generating non-XML-like content.  To avoid this, one can write a custom MarkupParser to define a Razor syntax for a different markup language (such as CSS).


The WebPages framework, in System.Web.Webpages.dll, is a set of classes to use with the Razor parser.  It contains the WebPage class which standard Razor pages inherit. This class defines the methods which are blindly called by the Razor parser, such as DefineSection and WriteLiteral.    This framework also handles _PageStart and _AppStart pages and contains the HtmlHelper infrastructure.

The WebPages framework is not directly connected to the Razor parser.  It could theoretically be used with a different template engine, as long as the template engine emits the correct method calls and class definitions.  (more on this later)

The WebPages framework also contains two sets of utility methods.  System.Web.Helpers.dll contains miscellaneous utility classes, such as Crypto and WebMail wrappers, plus grid and chart implementations.  Microsoft.Web.Helpers.dll contains HTML helper classes which integrate with various third-party services, including Twitter, ReCaptcha, Google Analytics, and more.  Most of these helpers can also be used in ordinary ASPX pages.

The source code for all of these projects is available here.

Next time: Gluing it all together.

Categories: razor, asp.net webpages, asp.net, dissecting-razor, .net Tweet this post

comments powered by Disqus