Saturday, April 18, 2015

How to create a Katana WebServer in a console application

Create a new Console app and add these 2 packages:

install-package Microsoft.Owin.Hosting
install-package Microsoft.Owin.Host.HttpListener

Add a class called Startup and a configuration method that takes an IAppBuilder interface. IAppBuilder is in the Owin namespace.

public class Startup
{
      public void Configuration(IAppBuilder app)
     {

             //Add other features from other Katana components through 
             //the Use extension method. For instance, this below method 
             // asfter installing the Microsoft.Owin.Diagnostics package
             // can be used instead of app.Run() to start a Web server 
             //with a Welcome Page.
             
             //app.UseWelcomePage();

              //Process all requests. Returns a task and is a wrapper to calling AppFunc.
              // app.Run can be used to dynamically add your middleware as done here.
              app.Run(ctx =>
              {
                    return ctx.Response.WriteAsync("Hello Katana!");
               });
      }
}

The IAppBuilder interface has methods that allows us to configure and respond to HTTP requests. As we add additional Katana components (nuget packages), we may see additional extension methods that we can use to turn on to use additional Katana features.

Run() takes an OwinContext which has an Environment property, and returns a Task. This property is a Dictionary<string,object> and has all the information about the request - the Http Headers, cookies, the URL path, the Verb that was used etc. This is the core abstraction of OWIN and makes it very simple to add Owin components and middleware as needed in the request processing pipeline. Does away with all the bells and whistles with the conventional ASP.NET and System.Web assembly processing pipeline.

To start the web server on say port 8080, use a Katana component called WebApp to run this Startup class as below:

public static Main(string[] args)
{
      string url = "http://localhost:8080";

      using (WebApp.Start<Startup>(uri)
      {
             Console.WriteLine("Web Server started....");
             Console.ReadKey();
             Console.WriteLine("Web Server ended...");
      }
}

Reference: This example has been taken from the Scott Allen Pluralsight course on OWIN.


No comments:

Post a Comment