joydip_kanjilal
Contributor

How to use Nancy in ASP.Net Core

how-to
May 13, 20194 mins
Microsoft .NETSoftware DevelopmentWeb Development

Take advantage of the lightweight and fast Nancy framework for building HTTP-based services in .Net Core

colorful origami birds in flight
Credit: Thinkstock

Nancy is a lightweight framework for building HTTP-based services. Nancy prefers conventions over configuration and provides support for GET, HEAD, POST, PUT, DELETE, and PATCH operations. Nancy is also open source under the MIT license. This article presents a discussion of how we can use Nancy with an ASP.Net Core application.

Nancy is a web framework and has no dependencies on System.Web or other .Net libraries. Most importantly, you are not constrained to adhering to the MVC pattern or any other pattern if you are using Nancy. Nancy is just a service endpoint that can respond to HTTP verbs. This makes Nancy a good choice for building websites, APIs, and web services.

Nancy is host-agnostic. You can run it in IIS, in WCF, as a Windows Service, embedded within an .exe file, or inside a self-hosted application. Nancy is quite easy to set up and customize. Another advantage of Nancy is its built-in support for dependency injection. Nancy also provides a library that can be used for testing the request-response cycle easily. I’ll discuss this feature of Nancy in a later post.

Create an ASP.Net Core project in Visual Studio

First off, let’s create an ASP.Net Core project in Visual Studio. If you don’t have Visual Studio 2019 installed in your system, you can download it here

To create a new ASP.Net Core project in Visual Studio 2019, follow the steps given below.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.Net Core Web Application” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create New ASP.Net Core Web Application” window, select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  8. Select “Web Application” as the project template.
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
  11. Click Create. 

You should now have a new ASP.Net Core project ready to go in Visual Studio. We’ll use this project in the sections below to build our custom hosted service.

Install and configure Nancy in ASP.Net Core

To install Nancy, right-click on your project in the Solution Explorer window and select “Manage NuGet packages…”. Then, in the NuGet Package Manager window, search for Nancy and install it. Alternatively, you can install Nancy from the NuGet Package Manager console using the following command.

Install-Package Nancy

Once Nancy has been installed, the next thing you should do is configure Nancy. To do this, you should call the UseNancy method in the Configure method of the Startup class as shown below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
     app.UseMvc();
     app.UseOwin(x => x.UseNancy());
 }

Create your first Nancy module in ASP.Net Core

So far so good. Let’s now create a Nancy module and write some code for it. A Nancy module is a standard C# class that extends the NancyModule class of the Nancy framework.

public class HomeModule : NancyModule
{
}

It should be noted that you must declare your Nancy module as public. The Nancy framework cannot discover a module that isn’t marked as public.

Create routes in a Nancy module in ASP.Net Core

A Nancy module defines the routes in its constructor. To define a route in Nancy, you should specify the HTTP verb, the pattern, the action, and (optionally) the condition. Here is an example that illustrates a Nancy route definition.

public class HomeModule : NancyModule
{
    public HomeModule()
    {
       Get("/", args => GetAllAuthors());
       Get("/{id:int}", args => GetAuthorById(args.id));
    }
}

In essence, a Nancy module is a place for defining HTTP endpoints. The following code snippet illustrates a Nancy module that can handle three different GET requests.

public class HomeModule : NancyModule
    {
        public HomeModule()
        {
            Get("/", args => "Welcome to Nancy.");
            Get("/Test", args => "Test Message.");
            Get("/Hello", args => $"Hello {this.Request.Query["name"]}");
        }
    }

Nancy is not only lightweight, modular, and fast, but installing and configuring it is quite easy. You can use Nancy to provide essential HTTP services with minimal effort. To learn more about the Nancy framework, you can refer to the documentation on GitHub

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author