Handling claims transformation in an OWIN middleware in .NET MVC part 1

Introduction

Claims have become widespread in software projects to tighten the security aspects of an application. We looked at claims before on this blog – see the link in the next paragraph – but time goes by and new features have been added to this technology lately. This is especially true as far as OWIN is concerned. In this mini-series we’ll concentrate on a very narrow aspect of claims in .NET MVC: claims transformation in OWIN middleware.

Read more of this post

Building a Web API 2 project from scratch using OWIN/Katana .NET Part 3: hosting on Helios

Introduction

In the previous post we discussed how to use OWIN host to self-host a Web API 2 application. We saw how easy and straightforward it was to install the OWIN hosting package with NuGet.

In this post we’ll look at another hosting option: Helios.

Read more of this post

Building a Web API 2 project from scratch using OWIN/Katana .NET Part 2: OWIN host

Introduction

In the previous post we saw how to build a simple Web API from scratch using a couple of OWIN/Katana components. We added a couple of Katana libraries from NuGet, wired up the routing from the Startup class and we were good to go.

In this post we’ll see one way to make the application run independently of IIS. As we stated before an important benefit of this new OWIN infrastructure is that you can make your ASP.NET web application run on multiple hosts, not only IIS. IIS is only one of the options.

Read more of this post

Building a Web API 2 project from scratch using OWIN/Katana .NET Part 1

Introduction

If you’re a .NET developer then you must have come across the new light-weight web framework standard called OWIN. Its implementation by Microsoft in .NET is called Katana. We’ve looked at OWIN/Katana on this blog already starting here. I won’t go through the same exact same topic in this new series. Instead we’ll concentrate on the basic components that are required at a minimum to build a functioning, platform independent Web API 2 project.

If you’ve read other posts on this blog then you’ll know about my preference for web services as opposed to shiny GUI development á la ASP.NET MVC. Also we’ll be looking into other Web API 2 features in OWIN later on so this will be a good foundation.

Read more of this post

OWIN and Katana part 4: Web API on top of OWIN

Introduction

In the previous post in this series we wrote a couple of OWIN middleware components and chained them together. We actually achieved quite a lot in a low level console application: it hosts a simple web server which receives HTTP requests, it processes the requests with Katana components and performs some elementary logging.

It’s now time to build an application on top of this environment. We’ll build upon the demo console app we’ve been working on so have it ready in Visual Studio. If you’ve read some other topics on this blog then you’ll note that I have a preference for the Web API as the server platform. So let’s see how we can build a Web API application on top of our little server.

Web API demo

Open the Console demo server in Visual Studio. We’ll need to install the following NuGet package:

Web API Owin Selfhost

As the package name implies this package will help us host a Web API 2.1 app using OWIN components. The package installs a number of other components such as WebApi.Core WebApi.Client, JSON.NET, etc. Open the References section in the Solution Explorer. If you’ve worked with the Web API before then some of those new libraries will be familiar to you: System.Net.Http, System.Web.Http and the like.

Add the following class to the project:

public class LatestNews
{
	public string Summary { get; set; }
}

We want our web service to show the latest news.

Let’s also add another class called LatestNewsController. It will be our first Web API controller. If you haven’t worked with the Web API before then a Web API controller has the same role as a “normal” controller in an MVC web app. It derives from the “ApiController” base class rather than the “Controller” class in MVC. The LatestNewsController class looks as follows:

public class LatestNewsController : ApiController
{
	public HttpResponseMessage Get()
	{
		LatestNews news = new LatestNews() { Summary = "The world is falling apart." };
		return Request.CreateResponse<LatestNews>(HttpStatusCode.OK, news);
	}
}

In Startup.Configuration comment out the Use method which dumps out the values in the Environment dictionary. The starting point for this exercise is the following “active” code, the rest should be commented out or removed:

public void Configuration(IAppBuilder appBuilder)
{
        appBuilder.Use(async (env, next) =>
	{
		Console.WriteLine(string.Concat("Http method: ", env.Request.Method, ", path: ", env.Request.Path));
		await next();
		Console.WriteLine(string.Concat("Response code: ", env.Response.StatusCode));
	});

	appBuilder.UseWelcomeComponent();			
}

Insert a new method stub in Startup.cs that will configure Web API:

private void RunWebApiConfiguration(IAppBuilder appBuilder)
{	
}

The key object to configuring the Web API is the HttpConfiguration object located in the System.Web.Http namespace. It opens, among a lot of other things, the gateway to the routing rules. Insert the following body to the above function:

HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.Routes.MapHttpRoute(
	name: "WebApi"
	, routeTemplate: "{controller}/{id}"
	, defaults: new { id = RouteParameter.Optional }
	);
appBuilder.UseWebApi(httpConfiguration);

This will look very familiar to you if you’ve done any MVC and/or Web API programming – which you probably have otherwise you wouldn’t be reading this post. So we set up out first routing rule using the MapHttpRoute method like in the standard Web API app template of Visual Studio. Finally we call upon the built-in extension of the IAppBuilder interface to declare that we want to use the Web API.

We should be ready to go. Add a call to this method from Configuration():

appBuilder.Use(async (env, next) =>
	{
		Console.WriteLine(string.Concat("Http method: ", env.Request.Method, ", path: ", env.Request.Path));
		await next();
		Console.WriteLine(string.Concat("Response code: ", env.Response.StatusCode));
	});

RunWebApiConfiguration(appBuilder);

appBuilder.UseWelcomeComponent();

Run the demo app and navigate to localhost:7990/latestnews in a web browser. You should see that our Web API component is indeed responding to the request:

Web Api output in web browser

We got the latest news in an XML serialised format. Also, you’ll notice that the middleware that prints the incoming request data in the console window still works:

Logging middleware still running

Now navigate to localhost:7990, i.e. without any controller name. You’ll see that our WelcomeComponent responds with “Hello from the welcome component”. The reason is that the web api component couldn’t route the request to any controller so it let the next component take over. The next component in the pipeline is the WelcomeComponent which happily responds to any request with the same message.

We have just built the basics of a self hosted Web API application which is very light weight, easy to extend and responds to incoming HTTP requests with meaningful data.

Deployment

Let’s try to deploy this application on IIS. Install the following NuGet package:

Owin host system web NuGet package

This package ensures that we can plug in our application into the ASP.NET pipeline.

We’ll also need to change a couple of other things in the application. IIS cannot directly load executables so our setup code in Program.Main is not relevant. Comment out the following chunk of code, all of it, including the Program class declaration:

class Program
    {
        static void Main(string[] args)
        {
			string uri = "http://localhost:7990";

			using (WebApp.Start<Startup>(uri))
			{
				Console.WriteLine("Web server on {0} starting.", uri);
				Console.ReadKey();
				Console.WriteLine("Web server on {0} stopping.", uri);
			}
        }
    }

All the startup infrastructure will be handled by IIS. However, we still want to run the Configuration code in Startup.cs. Open the project properties and turn the project type into a class library:

Turn console app into class library

Also, change the output path to simply ‘bin’ as is expected by IIS:

Change output path to bin

Build the solution to make sure it still compiles without errors. Check in the bin folder of the project that the [projectname].dll file was created by the build process. I called my project KatanaBasics so I have a KatanaBasics.dll in the bin folder. You’ll need the path to the bin folder in the next step.

We’ll use the iisexpress.exe file to load our this dll. The iisexpress.exe file is usually found here:

IISexpress.exe location

Open a command prompt and enter the following command. Make sure you enter the correct path as it appears on your system:

IIS express command prompt startup

…where the “path” parameter is the path to the bin folder on my computer. Press Enter and if everything goes well then you’ll see the following response:

IIS running in command prompt

You’ll notice in the output that IIS will be listening on port 8080 for this application. Navigate to localhost:8080 in a web browser and you should see that… …we get an exception, or at least I got it:

Missing owin assembly

Owin assemblies are updated quite often so it’s almost expected to run into this classic “Could not load file or assembly” error, although it’s really irritating.

Stop the IIS application by pressing “Q” in the command prompt. The solution is quite easy actually. The solution contains an app.config file with the following bit of XML:

<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />

This should do the trick of redirecting old references to an updated one. However, IIS won’t read this file as it is looking for a web.config file instead of app.config. Rename app.config to web.config. Then rebuild the solution, issue the same IIS command as before in the command prompt and navigate to localhost:8080. The WelcomeComponent should respond with “Hello from the welcome component”. Also, you should see the logging output in the command prompt along with some output from IIS itself:

Logging output with IIS running

The output of our OWIN middleware has been successfully plugged into the IIS infrastructure. Now check if the web api controller is still responding on localhost:8080/latestnews. You should see that it does indeed.

The OWIN project we’ve built produces a dll which can be referenced from any type of application: console, WPF, WCF, etc., it will always produce valid XML.

How was our application configured correctly now that the Program class has been commented out? How was our Configuration method called now that there’s no code calling it directly? The Host.SystemWeb dll has a bit of code that will look for a class called Startup and run its Configuration method for you automatically.

You can specify the location of the Startup in the appSettings section of web/app.config:

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

…where the value is the fully qualified name of the Startup class.

You can also specify it in the AssemblyInfo file:

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

If you don’t specify these values then it will try to find the Startup class through Reflection in the namespace matching the project name, in this case KatanaBasics. Since there’s one such class in that namespace, the web hosting process found it and executed it.

OWIN, Katana and MVC

Let’s see how OWIN and Katana are incorporated into ASP.NET MVC. In Visual Studio 2013 create a new MVC5 web application. Open the references list and you’ll see that there are several Owin related packages included by default:

Owin references in MVC5

You’ll also notice that there’s a Startup.cs in the root of the application:

Startup.cs in MVC5

Open the file and you’ll see the Configuration method which accepts an IAppBuilder object, so it follows the same pattern as we saw in our console based server app. The Configure method calls upon a method called ConfigureAuth. You’ll also notice the assembly metadata above the namespace that tells Katana where to look for the Startup class.

Note that this is a partial class so there’s one more Startup class. You’ll find it in the App_Start folder in a file called Startup.Auth.cs. This is where the ConfigureAuth method is implemented. As the method name suggests ConfigureAuth defines some OWIN middleware that have to do with authentication.

Most of the code is commented out. The two middleware functions that are not commented out are:

  • UseCookieAuthentication: to implement cookie authentication, checks if there’s a valid authentication cookie
  • UseExternalSignInCookie: for external cookies for third party auth providers

You can uncomment the rest of the code to activate either of the 4 available authentication providers: Microsoft, Twitter, Facebook and/or Google for OAuth2. We will look at these in a later series dedicated to security in MVC5.

Katana sourcecode

If you’re interested in how the Katana components are built then you can check out the sourcecode on the Katana Codeplex page. You’ll see the code for all existing Katana components there:

Katana codeplex page

You can even load the entire code from Git. You’ll find the git clone command on the Codeplex page.

View the list of MVC and Web API related posts here.

OWIN and Katana part 3: more complex middleware

Introduction

We wrote our first OWIN component, a.k.a. middleware in the previous part of this series. We said that it’s called middleware because it sits somewhere in the invocation chain of elements. There may be other elements before and after the actual component.

We’ll write a somewhat more complex component this time. We’ll build upon the simple Console based server application we’ve been working on in this series.

Demo

Open the Console based web server demo in Visual Studio 2013. In Startup.Configuration we currently have a call to appBuilder.UseWelcomeComponent. We’ll now insert another component that will execute before the WelcomeComponent.

Keep in mind that not all OWIN components must be separate classes. We saw an example of an inline component when we looked at the Run extension method. Recall that we could reference the Response property of the OWIN context directly instead of how we pulled it from the environment dictionary in WelcomeComponent which is at a lower level. The Run extension method does actually the same thing behind the scenes, i.e. it checks the environment variable and pulls the Response property out of it so that it is readily available from the OWIN context. That’s an example of how Katana can build upon OWIN to simplify things.

This time we’ll look at the Use extension method of IAppBuilder. It comes in two versions: one that takes a Func delegate, i.e. we can write an inline lambda expression, and another one which takes an object and and array of objects. This latter version allows us to pass in low-level components such as WelcomeComponent. The Func delegate has the following definition:

Func<IOwinContext, Func<Task>, Task> handler;

So it’s a delegate that returns a Task and accepts two parameters: an IOwinContext and another delegate which returns a Task. The IOwinContext will be the Environment, and Func of Task corresponds to the next component in the invocation chain. Insert the following stub into Configuration before appBuilder.UseWelcomeComponent:

appBuilder.Use((env, next) =>
{

});

In case you’re not familiar with lambdas start here. ‘env’ and ‘next’ correspond to the two input parameters of the delegate. You’ll see that the compiler is complaining as there’s no return statement in the body of the delegate. We’ll simulate some kind of logging in the body: loop through the values in the Environment dictionary and show them in the console. The Use method implementation looks as follows:

appBuilder.Use(async (env, next) =>
	{
		foreach (KeyValuePair<string, object> kvp in env.Environment)
		{
			Console.WriteLine(string.Concat("Key: ", kvp.Key, ", value: ", kvp.Value));
		}

		await next();
	});

The call to ‘next’ returns a Task and can be awaited, hence the ‘await’ keyword. We can write ‘next()’ because it represents the application function of the next component in the pipeline. And since the application function is a delegate, it can be invoked like a normal method. In order for that to work properly we had to add the ‘async’ keyword in front of the delegate declaration. Also, the Func delegate has to return a Task, which next() does, so it fulfils the delegate signature.

That was an example of middleware. Run the web server demo app and navigate to localhost:7990 in a web browser. Watch the values in the console. Some dictionary values are objects so their string representation will simply be the type name. Still, most values will probably look familiar to you as a web developer who’s done some work with HTTP requests and responses.

Let’s add another piece of middleware using the same technique. Insert the following code after the one we’ve just written:

appBuilder.Use(async (env, next) =>
	{
		Console.WriteLine(string.Concat("Http method: ", env.Request.Method, ", path: ", env.Request.Path));
		await next();
		Console.WriteLine(string.Concat("Response code: ", env.Response.StatusCode));
	});

First we report the HTTP method and the request path using the Request property of the Environment variable. Then we let the next component run and be awaited upon. Finally we print out the response status code. You could also overwrite the status code of course in another component. E.g. if a new resource is created with a POST method then you might want to return 201 Created instead of the default 200 OK.

Run the application again and refresh the browser with localhost:7990. You’ll see the new piece of information printed in the console: the method (GET), the request path (favicon) and the response code (200). You’ll notice that the request path in the dictionary dump is simply “/”, i.e. the application root and the response code to that is 200. Then we see another request in the second Katana component for the favicon. Refresh the web page a couple of times and you’ll see that the browser will try to fetch the favicon every time and respond with status code 200. You can also test with a different URL such as localhost:7990/donaldduck. You’ll see that the first request comes in for /donaldduck and then a second request for the favicon again.

Let’s see what happens if we reorder the invocation list. Recall that WelcomeComponent.Invoke doesn’t call upon the next component in the pipeline. In Startup.Configuration put appBuilder.UseWelcomeComponent to the top of the middleware list, i.e. ahead of the first Use method. Run the application and refresh the browser. You should see that the WelcomeComponent component is invoked but not the other two. So you see how the modular setup allows you to control and finegrain what’s happening in a web server when it receives a HTTP call.

Read the last post in this series here.

View the list of MVC and Web API related posts here.

OWIN and Katana part 2: the Application Function

Introduction

In the previous post of this series we started looking into OWIN and Katana. We also looked at a small, very basic Console based web server to see them in action.

We’ll continue digging into how these technologies work. We’ll build upon the demo application we started working on in the previous post so have it ready in Visual Studio.

The Application Function

The application function, or AppFunc is a tool that defines how elements process incoming HTTP requests to the server. It provides a delegate which returns a Task and accepts an IDictionary of string and object. We saw an example of such a Func in the first post of this series. The dictionary represents the request environment. Recall the Environment property of the IAppBuilder interface which is also of the same dictionary type. We also said that this structure is characteristic of OWIN as it lacks any higher level abstraction. It is not a dictionary of, say, RequestParameter and RequestKey with built-in properties which we could expect in a built-in object oriented .NET class. This particular dictionary includes all types of data about the request from and the response to the client: headers, cookies, server variables etc.

The application function delegate always returns a Task to adhere to the asynchronous programming model of modern .NET applications. At this point you should be familiar with the await-async keywords in C#. If not, then start here.

You’ll probably notice that this is quite low-level programming compared to writing a “normal” ASP.NET web application where you get all HTTP related tasks for free from the System.Web library and IIS as the default server. In OWIN you are free to build all components required to fulfil a request. The components will be independent from each other but still able to work together in a decoupled fashion. One component may check the request headers, another one the authentication cookies etc. Every component will have an application function that can be invoked externally. The components form a chain of actions where each component calls upon the next component’s application function in the pipeline using the data in the Environment dictionary mentioned above. As the dictionary object only contains strings and objects the chain remains very loosely coupled.

Demo

Open the console web server we started working on previously in Visual Studio. If you recall then we tested two methods of IAppBuilder: UseWelcomePage and Run. We’ll try something different this time. Add a new class to the solution called WelcomeComponent. Our goal is to write some greeting to every request at a lower level than we did previously. The class will need to come in contact with the IAppBuilder somehow. We’ll need to add a method that matches the Func delegate signature of AppFunc. Insert the following method stub into WelcomeComponent:

public Task Invoke(IDictionary<string, object> environment)
{
    throw new NotImplementedException();
}

Locate Startup.Configuration, comment out the call to appBuilder.UseWelcomePage and insert the following call instead:

appBuilder.Use<WelcomeComponent>();

The Use method will insert a component into the OWIN pipeline. Run the application and you should get an exception: MissingMethodException. The compiler is testing the OWIN components that you wired up using Reflection. If it finds any missing element it will tell you about it. In this case the error message says that “WelcomeComponent does not have a constructor taking 1 argument”. That argument is the AppFunc for the next component in the invocation chain. By now we know what an AppFunc delegate looks like so insert the following constructor stub:

public WelcomeComponent(Func<IDictionary<string, object>, Task> appFunc)
{
}

As an aside: there’s a little trick to make this constructor more concise. Add the following using statement underneath the others:

using ApplicationFunction = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

…the constructor becomes…:

public WelcomeComponent(ApplicationFunction appFunc)
{
}

The incoming appFunc variable represents the next component in the component chain. Add the following private field to the class:

private readonly ApplicationFunction _nextComponent;

…and so the constructor will look like the following:

public WelcomeComponent(ApplicationFunction appFunc)
{
	if (appFunc == null) throw new ArgumentNullException("AppFunc of next component");
	_nextComponent = appFunc;
}

We’ll also implement the Invoke method in a simplistic way:

public async Task Invoke(IDictionary<string, object> environment)
{
	await _nextComponent(environment);
}

So we await the next component and pass along the incoming environment variable to its constructor, just like the way how WelcomeComponent would be called in the pipeline.

A short aside: the Invoke method must be called Invoke, so I didn’t just pick this name. Change the method to something else, like MickeyMouse and then run the application. You should get a System.ArgumentException complaining about a conversion error.

Rename the method to ‘Invoke’. Add a breakpoint within the Invoke method and run the application. You should see a console window with the message that the web server has started. Navigate to localhost:7990 in a web browser and code execution should stop at the break point. Hover over the incoming ‘environment’ variable with the mouse to inspect its contents. In particular take a look at what’s available in the dictionary:

AppFunc dictionary contents

So there are 29 keys and 29 values – this number may change in future updates to the OWIN-related assemblies. Looking through the key names it will be clear immediately that it’s possible to extract just about any information related to the HTTP request: path, headers, request method, request body etc. This environment variable will make sure that the HTTP request properties will be available to every component in the chain. Some of them are actually specified as compulsory elements by the OWIN specification.

You can in fact stop the invocation chain right here and return a response to the caller already now. In that case you’ll need to access the “owin.ResponseBody” dictionary element. Stop the application and comment out the await statement in the Invoke method. The response body will be a Stream so we’ll extract it from the environment dictionary as follows:

Stream responseBody = environment["owin.ResponseBody"] as Stream;

We then construct a StreamWriter out of this and write to the response stream:

using (StreamWriter responseWriter = new StreamWriter(responseBody))
{
	return responseWriter.WriteAsync("Hello from the welcome component");
}

Remove the ‘async’ from the method declaration as the WriteAsync method already returns a Task. Run the application and navigate to localhost:7990 in a browser. You should see the plain message we provided above to the WriteAsync method. This was in fact a very low level Katana component, probably the lowest level possible.

The methods we tested with IAppBuilder, i.e. Run and UseWelcomePage, use the same technique behind the scenes. They are simply wrappers around a much more elaborate Invoke method.

We can make it so that our glorious implementation of the Invoke method becomes available to other programmers using an extension method. Add a new class to the project called AppBuilderExtensions:

public static class AppBuilderExtensions
{
	public static void UseWelcomeComponent(this IAppBuilder appBuilder)
	{
		appBuilder.Use<WelcomeComponent>();
	}
}

We can call this extension method in Startup.Configuration as follows:

appBuilder.UseWelcomeComponent();

This produces the same behaviour as before, just with a little nicer syntax. You’ll notice that the UseWelcomeComponent method call looks very much like UseWelcomePage – the implementation of the latter is probably slightly more involved however.

Components in OWIN are also called middleware as they sit in the middle of the processing pipeline. We’ll keep looking at OWIN middleware in the next post.

View the list of MVC and Web API related posts here.

OWIN and Katana part 1: the basics

Introduction

Katana is a new light-weight web framework built by Microsoft. It is based on a specification called OWIN – Open Web Interface for .NET. The default MVC5 template in Visual Studio 2013 have elements of Katana and OWIN.

Think of Katana as a web framework such as ASP.NET which interacts with IIS as the hosting environment. IIS provides a rich set of features for logging, tracing, monitoring etc. These features are not always needed. With the advent of HTML5 and some very advanced JavaScript libraries like jQuery, Knockout.js, Angular.js etc. a lot of work has been delegated to the client. It is often no longer the server that produces HTML – it only responds to Ajax calls with JSON and it is up to the client to process it. This applies especially to mobile applications that consume cloud based web services which only respond with JSON. The goal is to simplify web hosts to make them more responsive, more scalable and cheaper to maintain as the processing time of a request will be a lot faster. Node.js is a JavaScript-based framework that you can use to build a very lean and efficient web server which only has a limited number of features compared to IIS but suits the needs of a large number of web service consuming applications.

Katana allows you to build web based applications, such as MVC or Web API (2) where you can decide which web features to include in the project. Katana features are highly modularised. Instead of including the entire System.Web library even in the smallest web applications, you can decide which features to include and exclude. As mentioned above, Katana builds on OWIN to achieve these goals. OWIN is a specification which defines an an easy and decoupled form of communication between frameworks and servers. With Katana you can build applications that only indirectly use the features in System.Web through OWIN interfaces. Such an application can be hosted on any server that supports OWIN so it is not tightly coupled to IIS.

Normally a .NET MVC web application references the entire System.Web namespace which has a very large amount of features of which your application may only need a fraction. Also, it will be tied to IIS. Katana takes an other approach with its portable, modular and lightweight components.

I won’t test your patience any longer – let’s see a demo! We’ll build both a Console and a Web application so I have downloaded Visual Studio Express for Web and Desktop. If you have the full version of VS 2013 then you’ll be fine.

Demo

Open Visual Studio 2013 for Windows and create a new Console application. Call it KatanaBasics. Install the following NuGet packages:

Owin hosting nuget package

HttpListener owin package

The Hosting package will also install a number of dependencies such as Owin and Microsoft.Owin. These are the core Katana libraries. Owin contains the core OWIN abstractions, whereas Microsoft.Owin is the Microsoft extension to OWIN. The HttpListener library includes classes to communicate with the operating system. It also enables us to build a small app that listens to HTTP requests on a port. Which is what we’re planning to build here.

Add a new class to the project called Startup which will configure Katana. Be exact and call it “Startup”. When working with Katana you’ll see these Startup classes all the time. The Startup class must have a Configuration method which accepts an IAppBuilder object which resides in the Owin namespace. Add the following stub to the Startup class:

public void Configuration(IAppBuilder appBuilder)
{

}

IAppBuilder includes methods that help us configure an application, in particular how it will respond to HTTP requests. There are a lot of extension methods to the IAppBuilder interface. They are available in different Owin-related libraries. So as you reference additional Owin packages from NuGet you’ll see new extension methods available for the IAppBuilder interface. This provides you a way to enable new features as they become necessary.

The Run() extension method helps us configure how the application will handle HTTP requests. Katana will call into this method to process the requests. It accepts a Func delegate which returns a Task object and accepts an IOwinContext object as parameter.

Start typing the following within the Configuration method:

appBuilder.Run(owinContext =>
	{
		owinContext.
	});

This is a lambda expression that accepts an IOwinContext object which will be inferred by the compiler. As you type “owinContext.” IntelliSense will provide a list of interesting properties:

  • Authentication: to access properties of the current user, such as Claims
  • Environment: helps you to retrieve a range of OWIN-related properties from the current OWIN context
  • Request: to access the properties related to the HTTP request such as headers and cookies
  • Response: to build and manipulate the HTTP response

The Environment property returns a type of IDictionary of string and object which is quite generic and is characteristic of OWIN. Normally in ASP.NET we have access to strongly typed classes when we extract information about the incoming HTTP request. Here, however, the information is stored in a generic dictionary of the very basic “string” and “object” objects. OWIN aims to provide a simple API without a lot of specialisation.

In this very first demo we’ll only return a simple string to all callers using the Response property:

appBuilder.Run(owinContext =>
	{
		return owinContext.Response.WriteAsync("Hello from OWIN web server.");
	});

WriteAsync returns a Task so it is perfectly suitable for our Func delegate.

We’ll define the URI and port number in the Main method where the console app will be listening. We’ll also use another object from OWIN called WebApp to set up our web server. It is a Katana component residing in the Microsoft.Owin.Hosting namespace. It has a Start method where you can specify the class that includes your configuration. Add the following code to Main:

string uri = "http://localhost:7990";

using (WebApp.Start<Startup>(uri))
{
        Console.WriteLine("Web server on {0} starting.", uri);
        Console.ReadKey();
	Console.WriteLine("Web server on {0} stopping.", uri);
}

If you have anything running on port 7990 then select something else. All we do within the using block is let the world know that we’re starting the server. We can stop the server by pressing a button which is what the ReadKey is waiting for. That’s it really, we have just written a web server. Press F5 to start the application. You should see a console window popping up with the start-up message. Then open a browser and navigate to http://localhost:7990. You should see the welcome message in the browser:

Console web server running in browser

Let’s make the welcome page a bit more interesting. Download the following NuGet package:

Owin diagnostics NuGet package

The Diagnostics package includes the components to build a default home page. The IAppBuilder interface has now a new extension method available called UseWelcomePage. Update the Configuration method as follows:

public void Configuration(IAppBuilder appBuilder)
{
	appBuilder.UseWelcomePage();			
}

Start the console app again and navigate to localhost:7990. You should see a nice blue page such as this one:

Owin default homepage

We’ll dig deeper into OWIN and Katana in the next post.

View the list of MVC and Web API related posts here.

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: