Nancy, a micro web framework for .NET
Lately for a side project I have been poking at Nancy, the “micro web framework” that was born when Andreas Håkansson (a.k.a. @thecodejunkie) decided to port Sinatra-style syntax from the Ruby world over to .NET, and I love it’s simplicity.
While not quite as terse as it’s inspiration, I’m still impressed that you can write a “hello world” Nancy app in less than 140 characters:
This self-contained app will run inside an Empty ASP.NET Web Application with the Nancy.Hosting.Aspnet nuget package installed.
Sure, that gist wouldn’t fit in a tweet, but tweak a few names for brevity, and voila!
It’s all about Modules
Nancy is set up to organize your code into Modules like the simple one I quoted above. In the constructor of a Nancy Module you register a URL pattern and its handler by inserting the pair into one of the provided RouteBuilders (there is one each for Get, Post, Put, and Delete) via syntax that feels like dropping items into a Dictionary.
Handlers, in turn, take a single dynamic argument that is populated with URL parameters and must return a Nancy.Response which could range from a simple String or Stream to Nancy’s version of a View result.
Within the closure of your handler you also have optional access to the Module’s Request and Context properties (both custom POCO abstractions) with handles to the standard details including HTTP method, HTTP headers, QueryString values, request body, etc
Notice how the Request, Context, and Response objects are all unique to Nancy? I’ll come back to that later.
NancyModules allow you to organize your routes into related groups, and in a stroke of genius each Module can optionally pass a base URI to it’s ancestor, thereby nesting it’s routes under a common header, somewhat like ASP.NET MVC Areas:
This Module registers the following routes:
Another layer of abstraction
Remember those unique Request, Context, and Response objects?
The reason that is so exciting is that Nancy is completely abstracted away from any dependencies on System.Web and IIS; those live in the Nancy.Hosting.Aspnet nuget I mentioned above.
This means that your single app, as expressed through your Modules and related code, can be set up to run anywhere you like.
Futher reading on Nancy
- Nancy on Github
- a Video intro to Nancy
- Andreas’ blog
- Andreas on Hanselminutes
Stay tuned for more
Why, might you ask, would I be interested in Nancy? What nefarious side-project do I have cooking off to stage-left? Hopefully I can take off the wraps sometime in the next couple weeks.