#TIL: NancyFX Pipeline Injection

As you may know by following this blog or hearing me speak, I’m a huge fan of the NancyFX framework for .NET. Based off of Sinatra for Ruby, it makes creating web services a simple line or two of code compared to the more overweight methods built into ASP.NET or WCF. I knew about it for awhile, but last week I got to play with the Nancy Before and After Module Hooks to do some custom authentication.

With NancyFX, intercepting a request or response is as easy as adding a delegate method to the Before or After properties in your NancyModule classes.

Before += context => {
  return null or a response object;

This allows you to execute any sort of code before your normal service code gets a request, and then you can optionally pass through (return null) or return a response to immediately respond to and close the request. As you can imagine this is pretty handy for things like authentication, rate limiting, and other similar API cross-cutting concerns. If you have something you need to apply at an application level, you can also hook into the IPipelines.BeforeRequest, .AfterRequest, and .OnError pipelines as well by registering your own Bootstrapper class.

The only thing that’s a bit wonkey in this setup is the order of execution – there’s no clear cut way to define which before method should run first. Normally that isn’t an issue, but as you incorporate other modules and services you may run into a scenario where there’s a dependency – say you always want to do authentication first, or you always want to validate the rate limit before doing any pre-processing.

Oddly enough this is very similar to OWIN/Katana modules – they also provide functionality to allow you to define methods that take in a context of sorts, and return either null or a response. Wonder who copied who? (I’m guessing MS copied Nancy since Nancy’s been around longer, but who knows.)