Thursday, 17 July 2014

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 :)