Writing Your First OWIN Based Application

In my previous article ‘Getting Started With OWIN‘ we tried to understand what is OWIN and Katana and why they are needed. In this article Writing your first OWIN based application, we will be looking at a simple demo application. This will allow us to start a webserver and return some content with a console application using the OWIN wrapper provided by Katana.

Pre-requisites

I have written this application using Visual Studio 2017 Community and .Net Framework 4.6.1. Hence kindly make sure that you match the pre-requisites for the same. I am not sure but it should run in previous versions of Visual Studio uptil VS 2013 I guess.

Step-By-Step Demo

1. Open Visual Studio and create a new project (OWINDemo) by selecting Console App. Make sure that you are not selecting the .Net Core section as it uses OWIN by default. Hence we need to create a normal console app as shown below:

NewProject
Image source: Microsoft Docs

2. Right click this project and select properties. This is just to make sure that you have created the right project and the framework:

Prj_Prop
Image source: Microsoft Docs

3. In order to use OWIN, we will need to get the nuget packages for the same. Right click on ‘References’ in the console application and click ‘Manage Nuget Packages’

Manage Nuget
Image source: Microsoft Docs

4. Search online for ‘Microsoft.Owin.Hosting‘ and install it. Accept any terms and conditions that come up.

Add OWIN reference
Image source: Microsoft Docs

5. Similarly, Search online for ‘Microsoft.Owin.Host.HttpListener‘ and install it.

6. Now right click on your project in Visual Studio, choose Add and select the below item from the ‘Add New Item’ dialog box – “OWIN Startup class“.

Note: If you are using VS 2012, add a new empty class named Startup, and paste above code. The class template is available in VS 2013.

OWIN Add new item
Image source: Microsoft Docs

Make sure you rename it as ‘Startup.cs‘ as by default it might be named as ‘Startup1.cs‘. After adding the class, also rename any other instances as well.

7. Adjust the default code in the ‘Startup.cs’ file to align with the below code:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

namespace OWINDemo
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(context =>
            {
                context.Response.ContentType = "text/html";
                return context.Response.WriteAsync("<h1>Owin Demo Application</h1>");
            });
        }
    }
}

Notice the line app.Run(context =>
If you hover over the Run method, it will give you an intellisense something like the below:

StartUp class
Image source: Microsoft Docs

If you read my previous article ‘Getting Started With OWIN‘, I mentioned there that the OWIN specification expects us to use a signature which is something as below:

Func<IDictionary<string, object>, Task>;

This is exactly what the wrapper allows us to do. This code adds a simple piece of middleware to the OWIN pipeline, implemented as a function that receives a Microsoft.Owin.IOwinContext instance. When the server receives an HTTP request, the OWIN pipeline invokes the middleware. The middleware sets the content type for the response (in our case, it is set it to “text/html”) and writes the response body.

8. Open the Program.cs file and add the following code:

using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OWINDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            WebApp.Start("http://localhost:5001");
            Console.WriteLine("Server up and running...");
            Console.ReadLine();
        }
    }
}

9. Compile and run the above program and it will start the webapp as follows:

command prompt
Image source: Microsoft Docs

10. Now browse to the url mentioned in the code and you will see that without using any web server we are able to host our code in the browser.

browser run
Image source: Microsoft Docs

That is OWIN in action as we have created a http pipeline from our application which it detected by using the Startup.cs file and returned back the response in html format. Notice that is also recognized the tags we have specified.

You can find more detailed information at
https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/getting-started-with-owin-and-katana

Role of the ‘Startup.cs’ file

You might be thinking what role does the Startup.cs file play and how does OWIN find this file. The Startup file is the one place where OWIN-related code will be written by the application developer and it will be the application startup code, where the developer creates the OWIN pipeline. In the startup code, the developer registers a series of statements, generally one for each middleware component that will process incoming requests. This will have the same effect as registering HTTP modules with our application. Typically, a larger framework middleware, such as ASP.NET Web API or SignalR will be registered at the end of the pipeline. Common middleware components, such as authentication, caching, etc. are generally registered towards the beginning of the pipeline so that they will process requests for all of the frameworks and components registered later in the pipeline.

‘Startup.cs’ file detection

When you are using OWIN, it will try to find a Startup file using the following approaches:

1. Naming Convention: It looks for a class named Startup in namespace matching the assembly name or the global namespace. This is the approach which our demo application uses.

2. OwinStartup Attribute: This is the approach most developers take to specify the startup class. The following attribute will set the startup class to the Startup class in the OWINDemo namespace.

[assembly: OwinStartup(typeof(OWINDemo.Startup))]

3. appSetting in config file: This overrides the naming convention and the OwinStartup attribute and . You can have multiple startup classes (each using an OwinStartup attribute) and configure which startup class will be loaded in a configuration file using markup similar to the following:

<appSettings>  
    <add key="owin:appStartup" value="OWINDemo.Startup" />
</appSettings>


Summary

In this article, we saw step-by-step how to integrate OWIN as a middleware in our application. Hope you enjoyed both the Getting Started With OWIN and writing your first OWIN based application.

Hitesh Boricha

I have a little over a decade experience in the IT industry. Having worked in various roles in this industry, I am passionate about technology.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.