TopMenu

Thursday, 17 July 2014

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 pipeline2. 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.SelfHost

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.

publicclass Startup

{

publicvoid 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.

publicstaticclass Program

{

publicstaticvoid Main(string[] args)

{

conststring 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.Let’s launch the browser and check the Url where we have our host available for serving: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.WebApiNow ofcourse you need to create a WebAPI controller. So let’s do that:

publicclass TestController : ApiController

{

publicint[] GetValues()

{

returnnewint[] { 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.

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

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:

publicenum 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.

Tuesday, 15 July 2014

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. 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

publicclass Startup

{

publicvoid 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.

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>

publicclass Startup

{

publicvoid Configuration(IAppBuilder app)

{

app.Run(context =>

{

context.Response.ContentType = "text/plain";

return context.Response.WriteAsync(this.GetUserAgentInfo(context));

});

}

privatestring 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 browserGoogle chromeInternet Explorer 11This 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

publicclass Startup

{

publicvoid 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.

Let’s run the server by hitting F5 again and see what happens. Output: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.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.