Skip to content

Lets Play With Nancy!

Misleading title…I know 😉

I have just discovered Nancy when I was trying to find a way to decouple the MVC element from my ASP.NET applications. I knew there had to be a way! It is very easy to decouple your Web API stuff using the readily available Owin packages (Microsoft.AspNet.WebApi.Owin).

How easy is it to set up?

It’s bloomin’ easy! I managed to get some simple output with only 2 files! Which is great, considering the default MVC scaffold has a whole lot of files.

Where do I begin?

So you’re ready? Okay, lets play with Nancy! 😀

You will need to run these 2 commands from the Package Manager Console:

Alternatively you can use the "Manage Nuget Packages" option when you right click on the "References" item on the solution explorer.
Alternatively you can use the “Manage Nuget Packages” option when you right click on the “References” item on the solution explorer.

Next we need to add a Startup file, which is the entry point for an Owin web application.
The great thing is that it only takes a few lines of code 🙂

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(NancyBooks.Startup))]
namespace NancyBooks
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseNancy();
        }
    }
}

Nancy Modules

Modules are just like the Controllers of a standard MVC web application. Although there is one major difference. Unlike with a standard MVC app, you will have to define your methods and routes manually from within the module. For people who have been using Attribute Routing this should feel quite normal.

I guess it is time to show you how simple this actually is!

using Nancy;

namespace NancyBooks.Modules
{
    public class HomeModule : NancyModule
    {
        public HomeModule()
        {
            Get["/"] = _ =>
            {
                return "Hello, World";
            };
        }
    }
}

This will just print Hello, World on to the / route.

What did I tell you?!

Two files, and we already have a functional MVC application.

Whats next?

There is a lot more stuff that Nancy can do. And I will write another article soon on its additional features, such as model validation, and being able to use Razor views with your routes.

Published in.NETC#C#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *