Introduction to Nancy

02 maart 2022 om 10:00 by ParTech Media - Post a comment

Let’s begin this post with a simple example. Whenever you go to purchase a car, you will find the dealer to be selling it with some stock parts. Now, if you wish to make any modifications to the car, such as replacing the existing sound system, you can also do so aftermarket.

On similar lines, we develop applications using certain programming languages and frameworks. In case we want to change certain areas of it with different ones, then is it totally possible. For instance, ASP.Net framework applications are usually considered slightly heavy to handle. To address this, we have a lightweight open-source framework called Nancy. Let us see everything about Nancy in this blog.

Table of contents

  1. Introduction to Nancy framework
  2. Hands-on with Nancy framework
  3. Conclusion

Introduction to Nancy framework

Nancy is a lightweight, powerful, open-source, and simple web framework designed to handle HTTP-based web requests like GET, PUT, POST, DELETE, etc. Nancy can be consumed in ASP. NET-based applications by installing them from the NuGet package manager. Nancy has an in-built TinyIoC, which resolves the dependencies automatically. It provides the ability to develop applications with fewer lines of code and fewer lines of configuration. And, it has an in-built testing framework that can be used to test end to end (request to response cycle).

Hands-on with Nancy framework

In this section, we are going to try using Nancy in an ASP.Net-based application. We are going to create a Nancy-based API service as well as a website.

First, let us build the Web API.

Create an ASP.Net Core-based web API project with .Net 5 as the framework and provide a valid name to the project.

Once created, the predefined template of the project looks like below.

The next step is to install the required packages. Install the below packages from the NuGet Package Manager (Right-click the project and choose Manage NuGet Packages).

  1. Nancy
  1. Microsoft.AspNetCore.Owin

Once installed, go to Startup.cs file and add the below changes in Configure method right at the top.

app.UseOwin(x => x.UseNancy());

The next step is to create a separate Module/Controller for Nancy. To do that, right-click on the Controllers folder and click Add -> Controller. Now select the MVC empty controller and add the below lines of code inside it.

public class NancyController : NancyModule
  {
​    public NancyController()
​    {
​      Get("v1/gettingstarted/{name}", args =>
​      {
​        string name = args.name;
​        var response = $"Hello {name} !, Welcome to PARTECH.";
​        return response;
​      });
​    }
  }

The above code holds a GET method that returns the name provided in the query string.

To test the changes, run the solution. By default, the application opens the swagger. To test it, it can be done either using the browser or by using tools like Postman. Here, we will be testing it using the browser. Open a new tab and enter the below URL (the portal number might change).

https://localhost:44367/v1/gettingstarted/nancy

Did you notice the below output on your screen? Similarly, we can use POST, PUT, DELETE REST protocol operations in Nancy based on the requirements.

The next step is to implement Nancy WebApp, which is more or less similar to the Nancy WebAPI. The only difference is that instead of returning the data from the Module methods, required views and their data are rendered just like the MVC pages in ASP.NET. Let's now understand how to implement the same.

To begin with, create an ASP.Net Core Web App (MVC) with either an empty project or with the predefined template and provide a valid name to the solution. In this example, we are implementing Nancy with .NET5.

Once created, the predefined template structure looks like below.

To implement Nancy, we need to have a few NuGet packages installed similar to the last section.

Install Nancy and Install Microsoft.AspNetCore.Owin from the NuGet package manager.

Once installed, similar to controllers, Nancy has its NancyModule. Let's create a Module(the equivalent of the controller) that inherits the NancyModule. This can be created anywhere - If it is an empty project, then it can be created under the Modules folder, or if the predefined project template is used, then it can be created under the controllers' folder too.

Once created, add the below lines of code to the HomeModule.cs file.

using Nancy;
namespace PARTECH_NancyWebApp.Controllers
{
  public class HomeModule : NancyModule
  {
​    public HomeModule()
​    {
​      Get("/", args =>
​      {
​        dynamic viewBag = new DynamicDictionary();
​        viewBag.WelcomeMessage = "Hello, Welcome to Nancy!";
​        return View["home", viewBag];
​      });
​    }
  }
} 

In the above example, a viewbag (it is a dynamic object property that can be used to pass data from controller to view. As it is dynamic, it can take any format) is being created in the code, where some data that needs to be sent to the view is added. And in the last line, the view that needs to be called for this action method is provided.

Nancy generally looks for the view file in multiple places. One common place is under Views folder and home.html or Views/Home/Home.HTML. It supports file formats such as HTML, htm, and sshtml. Here we are going to create the home.html directly under the Views folder and consume the viewbag data that is sent from the Module.

Create a file under Views and name it as home.html. Add the below lines to that file.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>PARTECH - Welcome!</title>
</head>
<body>
  <h1>@Model.WelcomeMessage</h1>
</body>
</html>

Now right-click on the home.html file, go to properties and choose ‘Copy to Output Directory - Copy Always.’

Now, we are good to go for executing the solution - Hit F5.

Did you observe - by default, the above page gets loaded for the application?

Conclusion

In this post, you have seen been given an overview of Nancy and how it is extremely useful for developers to implement web applications and API. So use it in your next application and enjoy the benefits of writing a program with fewer lines of code and fewer lines of configuration.

Nieuwste