TopMenu

Self Hosting OWIN and Asp.net WebAPI

In this fourth blog post of the OWIN and Katana series, we’ll be discussing about the various hosting options available for Katana. As the OWIN specification said the server and host are separated so we can use a list of types of host to host the OWIN middleware i.e. Katana. The application will be working in a normal hosting environment.

Warning: - This article is valid with the version of Microsoft.Owin.SelfHost 2.1.0.

Let’s first discuss why Katana was provided with the various hosting types. In legacy framework of Asp.net the only available option was using System.Web or IIS. We have already seen the Hosting of Katana in the IIS in our previous posts.
In the initial phase of releases the Katana was supposed to support the following hosting types:
1. Asp.net IIS hosting pipeline
2. Owin self host

First we’ll discuss how to start a self host for OWIN. As the new release are coming for the Katana the more it’s becoming a more charming and easy to use in a way of usability. The documentation MSDN i.e. Asp.net website is outdated. So I've placed a disclaimer in the start of this article too ;)
Let’s fire up the VisualStudio and Add a new project -> Console Application.
Install the pre-requisite –

Install-Package Microsoft.Owin.SelfHostclip_image002

Now we need Startup.cs class that would be identified as Configuration setup class. The naming is important for this class and should be named as Startup. If you’re interested in knowing detection of Startup for OWIN read this post OWIN Startup Class detection.

Here’s the supplementary package for you.

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        // Those who are familier with HttpContext, owinContext is just a brother from another mother.
        appBuilder.Run((owinContext) =>
            { 
                owinContext.Response.ContentType = "text/plain";
 
                // here comes the performance, everythign in the Katana is Async. Living in the current century.
                // Let's print our obvious message: :)
                return owinContext.Response.WriteAsync("Hello World.");
            });
    }
}

For more options -


Install-Package Owin.Extensions


This will provide you lots of extension method with various options to invoke the Usage, StageMarker, Map functions. Go as you like.
Now let’s add some code in the Main function to start the code.


public static class Program
{
    public static void Main(string[] args)
    {
        const string baseUrl = "http://localhost:5000/";
 
        using (WebApp.Start<Startup>(baseUrl))
        {
            Console.WriteLine("Press Enter to quit.");
            Console.ReadKey();
        }
    }
}
Now you’re ready to roll. Run the console application hitting F5 in visual studio and you’re on.
clip_image003
Let’s launch the browser and check the Url where we have our host available for serving:
clip_image004

There it is. No IIS, No System.Web, Individual recipe for you.
Now let’s do something interesting. The Katana is best support for SingalR and WebAPI until now because both of these technologies are completely independent of System.Web i.e. Asp.net IIS.
To host an WebAPI in our custom host just follow below steps:
Install the pre-requisites –


Install-Package Microsoft.Aspnet.WebApi
clip_image006Now ofcourse you need to create a WebAPI controller. So let’s do that:


public class TestController : ApiController
{
    public int[] GetValues()
    {
        return new int[] { 12, 13, 14, 15 };
    }
}


That’s not all, It’s all about Nuget don’t leave the cart we’re still travelling to the shore.
Install the WebAPI support via Nuget:


Install-Package Microsoft.AspNet.WebApi.Owin



Now go back to the Startup.cs and add few configuration that, ofcourse, required to start an WebAPI.



public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        // Setup WebAPI configuration
        var configuration = new HttpConfiguration();
 
        configuration.Routes.Add("API Default", new HttpRoute("{Controller}"));
 
        // Register the WebAPI to the pipeline
        appBuilder.UseWebApi(configuration);
 
        // let's keep the old stuff too.... 
        // Those who are familier with HttpContext, owinContext is just a brother from another mother.
        appBuilder.Run((owinContext) =>
            { 
                owinContext.Response.ContentType = "text/plain";
 
                // here comes the performance, everythign in the Katana is Async. Living in the current century.
                // Let's print our obvious message: :)
                return owinContext.Response.WriteAsync("Api is availble at:  /Test");
            });
    }
}


So let's open the default page that will serve the Normal http content:
image
I have used simply the controller name to invoke the WebAPI controller function. Which make sense for the demo. Now let’s try this in Chrome not in i.e. Because it will ask you for action to save the Json format file. Our url will be http://localhost:5000/Test.
clip_image008
But this not JSON right? OK, I’m gonna give an interesting tip to open any WebAPI method that returns a JSON. If you have Git Bash installed, then Launch it and run following command Curl with Url of your WebApi url. This supports invoking any Web http request that gives JSON in response in a formatted result as output.
clip_image009

Hope you would love this way to get the JSON in a formatted way. So I enjoyed writing this article hope you enjoyed reading it too.
See you on the other side of OWIN. Give a holler :)

OWIN Katana and Stage Marker in Asp.net Integrated pipeline

This is third post in the series of blog posts on OWIN and Katana.
i) Basics of OWIN and Katana
ii) OWIN middleware-Asp.net integrated Pipeline extensions in Katana

In previous post of this post we discussed about the Asp.net integrated pipeline and HttpModule. How to add your custom OWIN middleware component? In this post we’ll be learning about the various stages of Asp.net Integrated pipeline and how to register and run your OMC at a specific stage.

Below is the list of various stages available in the Katana which acts as a OWIN middleware:

public enum PipelineStage
{
    Authenticate = 0,
    PostAuthenticate = 1,
    Authorize = 2,
    PostAuthorize = 3,
    ResolveCache = 4,
    PostResolveCache = 5,
    MapHandler = 6,
    PostMapHandler = 7,
    AcquireState = 8,
    PostAcquireState = 9,
    PreHandlerExecute = 10,
}
Now if you want to run your code at specific stage you just need to register your OMC with the stage. This can be performed with the help of StageMarkers in OWIN. So let’s create or use our previous OMC and run it at a specific event. In this demo let’s use the stage of Authentication and run our OMC during the Authroization stage in the Asp.net Pipeline.


using AppFunc = Func<IDictionary<string, object>, Task>;
    using Microsoft.Owin;
 
    public class Startup
    {
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder builder)
        {
            // Middleware created with in startup class.
            builder.Use(new Func<AppFunc, AppFunc>(ignoredNextApp => (AppFunc)Invoke));
 
            // Specify the stage for the OMC
            builder.UseStageMarker(PipelineStage.Authenticate);
        }
 
        // Invoked once per request.
        public Task Invoke(IDictionary<string, object> environment)
        {
            string responseText = "Hello World";
 
            // writing response header asynchronously
            byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);
 
            // See http://owin.org/spec/owin-1.0.0.html for standard environment keys.
            Stream responseStream = (Stream)environment["owin.ResponseBody"];
            IDictionary<string, string[]> responseHeaders =
                (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
 
            responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
            responseHeaders["Content-Type"] = new string[] { "text/plain" };
 
            return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);
        }
    }

Similary you can any of the stage listed above and customize the Asp.net pipeline to process your request or response.

In our next blog post we’ll be talking about the self host OWIN process. Say no to System.web and run your web request on an individual server with no boundation of Plateform or host/server.

OWIN middleware-Asp.net integrated Pipeline extensions in Katana

OWIN Middleware components (OMC) to that of an HttpModule in the ASP.NET world, an OMC must be registered to the correct pre-defined pipeline event. In this article we’ll see how to create a middleware and register it with the pipeline event. Also default stage for the middleware execution in the pipeline. So let’s get started:

1. Create an empty Asp.net website.
clip_image002
2. Install the Microsoft.Owin.Host.SystemWeb Nuget package. You can either use the Nuget package manager UI from visual studio or directly run the below command in the Nuget package manager console:

Install-package Microsoft.Owin.Host.SystemWeb

This command will install the package library and other dependencies which includes “Owin”, Microsoft.Owin”. Note that the package Microsoft.Owin.Host.SystemWeb is support for System.Web in Owin.

3. Create a Startup class and here you can configure the startup of the server e.g. registering custom pipelines for stages, we’ll talk about about pipeline stages in later posts. Also host server will be supporting full debugging with in visual studio. Let’s just create a simple server startup configuration.

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Run(context =>
            {
                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync("Hello Katana World!!!");
            });
    }
}

Run the server with F5. The host will be running on localhost:55666 port showing output like this.
clip_image003

As a default behaviour since we are using the SystemWeb the server will be serving the content using the Asp.net pipeline which in fact is IIS server. Now let’s now use the IIS server and use a little lighter host server to run our webapplication.

That was the simplest example of create an Asp.net IIS hosted application. Let’s do something interesting to understand the abstraction and flexibility between the server and application.

Let’s create a sample startup configuration that will display the information about the browser agent by reading the request header. Just update the code in the Configuration method of Startup class.

Startup.cs


/// <summary>
/// Implements the startup behavior for the host server.
/// </summary>
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Run(context =>
        {
            context.Response.ContentType = "text/plain";
            return context.Response.WriteAsync(this.GetUserAgentInfo(context));
        });
    }
 
    private string GetUserAgentInfo(IOwinContext context)
    {
        return context.Request.Headers.Get("User-Agent");
    }
}

So I get the information about the User Agent for different browser:

Visual studio Inbuilt browser
clip_image005
Google chrome
clip_image007
Internet Explorer 11
clip_image008
This was simple isn’t it, let’s take a little dive with in and create some Middleware to interpret the request and response. We can create owin middleware implementation by two ways.
1. Creating a separate class for each Middleware for pipeline.
2. Using the Func delegate template and use it with in the Startup class.

First let’s create a BasicMiddleware to use in the pipeline. Also let’s add some code to see when this Middleware will be going to execute. Here’s the complete code for the class. In this class we’re adding a user item in the response header. That’s it.

BasicOwinMiddleWare.cs



public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Run(context =>
            {
                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync("Hello Katana World!!!");
            });
    }
}


Startup.cs


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Owin;
using System.Collections.Generic;
 
namespace Katana.HelloWorldServer
{
    using AppFunc = Func<IDictionary<string, object>, Task>;
    using Microsoft.Owin;
 
    // Note the Web.Config owin:AutomaticAppStartup setting that is used to direct all requests to your OWIN application.
    // Alternatively you can specify routes in the global.asax file.
    public class Startup
    {
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder builder)
        {
            // Custom middleware in separate class.
            builder.Use<BasicOwinMiddleWare>();
 
            // Middleware created with in startup class.
            builder.Use(new Func<AppFunc, AppFunc>(ignoredNextApp => (AppFunc)Invoke));
        }
 
        // Invoked once per request.
        public Task Invoke(IDictionary<string, object> environment)
        {
            string responseText = "Hello World";
 
            // writing response header asynchronously
            byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);
 
            // See http://owin.org/spec/owin-1.0.0.html for standard environment keys.
            Stream responseStream = (Stream)environment["owin.ResponseBody"];
            IDictionary<string, string[]> responseHeaders =
                (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
 
            responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
            responseHeaders["Content-Type"] = new string[] { "text/plain" };
 
            return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);
        }
    }
}
(Snippet taken from: Katana samples)

Let’s run the server by hitting F5 again and see what happens.
Output:
clip_image009
As you can see the new item in the Response header is captured. Now let’s look at the stage of the pipeline as we did some tracing to get the stage when the response header was updated.
clip_image010
So Now we know the default stage to execute the Owin middleware is PreExecuteRequestHandler event. But here comes the interesting fact, You can customize this stage by using the StageMarker.

We’ll discuss this in our next post, How to run the middleware during various Asp.net pipeline stage events? Also, how to use a custom OWIN self-hosting process to host the web application? Don’t miss it.

References:
http://www.asp.net/aspnet/overview/owin-and-katana
http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana
http://owin.org/spec/owin-1.0.0.html