Behind the Scenes of OWIN (Open Web Interface for .NET)
Tags: owin, dotnet, httpabstraction, webdev
Published: 2024-06-26 09:32:54

In this article, we will understand what OWIN is and its history of how it was created. The article will helps to who are wondering behind it.

And we will understand how a group of people brought valuable ideas to the .NET community. Also important is the fact that Microsoft has embraced OWIN and ASP.NET Core is basically built on this idea.

Let’s get started!

In simple term, OWIN is the acronym of Open Web Interface for .NET and it is a specification that provides to decouple web servers with web applications. This specification is an also open standard for all .NET ecosystems.

The [officially](http://owin.org/#about) OWIN is — _“defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.”_

The word “specification” can confuse you but it means standardized contracts/interfaces which provide how communication between web servers and applications should be. So, these things are not concrete implementations rather it is telling developers how to communicate between web servers and web applications.

## The Story

The story of OWIN began (2010) with a group of people who were inspired by other programming language libraries and they were trying to create a library that provides HTTP abstraction between web servers and web applications/frameworks.

One day a group of people who were working on their own framework/library, Ryan Riley (the creator of Kayak) sent an email to others who were working on its framework/library about sharing knowledge and working together (because they were working on the same and different but complementary things).

September 7 (2010), The first email sent by Ryan Riley is shown below;

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zsrx4zltcxc155o0w1g8.png)

Then the group started discussing it together because the message made sense. And they started to collaborate through the google group.

First of all, the group was meet for find out solution for the problems. The main problems were:

- ASP.NET was coupled to IIS (System.Web.* packages)
- ASP.NET was too heavy
- IIS was to slow (old versions)
- Hard to do REST (like minimal API, Sinatra -> DSL things)

In addition, the .NET community needed decoupled/independent, lightweight and efficient web frameworks that worked with different lightweight web servers.

So, the group people started to solve it with inspiration from **Rack** (Ruby) and **WSGI** (Python). In simple term, **Rack** and **WSGI** define a common interface between a web server and a web application.

September 27 (2010), the first draft came from Benjamin van der Veen;

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xveqjl0ewhp459o20zh3.png)

As you can see the idea stands on Responder, Request and Response interfaces. (It provides certain abstraction from the server side and provides abstraction by Request and Response passed to the application side. The idea provides standardization with interfaces)

November 29 (2010), one of the people (Scott Koon) from the group created a working group under the name “.NET HTTP Abstractions” (check it out google group).

The group of people has come to a consensus about web server wrappers. At the same time, the Open Web Interface for .NET (OWIN) nomenclature was decided upon and the specification started to be written.

Also, at the beginning of the specification, the group of people declared goals;

- No dependencies
- Flexibility of style
- Server independence

Well, during the writing of the specification, some problems were of course encountered (I will skip this part, if you want more details you can check out the google group and website links).

After some brainstorming and experimentation, the group of people found the following solutions, which shown below;

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pnzcxadbg8zy2it2yfk.png)

They were concentrated on “Delegate Of Doom” (informal term) which restricted pattern or technique that provides minimal dependency and contract (standardization) for communication between web server and application. The idea was to create a communication contract + communication pipeline.

And they had decided to create gate reference (entry point) which represent helper library for who wants to start using OWIN standard. And the library is open source in [Github](https://github.com/owin).

On July 25, 2011, the OWIN project was publicly announced, marking the beginning of a collaborative effort to create the specification.

And, finally, in December 2012 the OWIN project had been released its first official version 1.0.

## OWIN
In this section, we will cover the general idea. The specification details will not be considered, [click](http://owin.org/html/spec/owin-1.0.html) if you are interested in the more details.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ow3cc51s0s5diebb945j.png)

The image shown above gives a bird’s eye view of OWIN. As I said before, OWIN is just provides decoupling communication between web server and web application. But take into account that OWIN is not framework, library or implementation. If you look at the OWIN specification you will get details of rules or samples of code on how web servers and applications communicate with each other.

To get into the details, it is necessary to start with the actors, which helps to understand the idea of OWIN.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7gpr0m51ynyd2u8zcroq.png)

- **Web Framework** — A self-contained component on top of OWIN exposing its own object model or API that applications may use to facilitate request processing. Web Frameworks may require an adapter layer that converts from OWIN semantics.
- **Web Application** — A specific application, possibly built on top of a Web Framework, which is run using OWIN compatible Servers.
- **Middleware** — Pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose.
- **Server** — The HTTP server that directly communicates with the client and then uses OWIN semantics to process requests. Servers may require an adapter layer that converts to OWIN semantics.
- **Host** — The process an application and server execute inside of, primarily responsible for application startup. Some Servers are also Hosts.

Mainly, the actors must-have for any web applications. So, OWIN dictate to all of them to achieve goals.

**Note that for understandable explanation I will describe all processes with runtime things. Some parts of the explanation may be outside the scope of OWIN.**

The communication between a web server and a web application (top of the web framework). For that reason, these actors also have a huge computational logic. The idea brought the pipeline for handling web requests and responses lifecycle. This is also relies on Pipeline architecture which provides to achieve cross-cutting concerns between web servers and web applications.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhez8ldt3q75aruu8u82.png)

Everything starts with a host which creates the needed environment and configuration things. In runtime should consist of a built-in web server and application which is top of a framework. So, basically web server listens to HTTP requests populate things some data structure and send to the communication pipeline.

The idea of building a pipeline starts with middleware, which is a chain or filter for all its parts. The middleware provides some cross-cutting concerns and helps to handle requests and responses lifecycle. When requests are coming from the server send them to the first chain/filter (middleware) and then requests will continue one by one with each other. And end of the pipeline requests are handled with the application and generate the response, the same things happen with response in a back way.

So far we have explained the general idea, you can look at the specification for more details.

Solution of OWIN start with;

```csharp
using Environment = IDictionary<string, object>
using AppFunc = Func<Environment, Task>
```
Hmm, it’s a little easier than you think!

- **Environment** is the key-value pair that contains all needed data including request and response objects. So, it makes sense when the server and application communicate with each other!
- **AppFunc** is the delegate that provides handling requests.

Basically, how AppFunc handle requests on an Application side? Code is shown below;

```csharp
using System.IO;
using System.Text;
using Headers = IDictionary<string, string[]>;

var app = AppFunc(env => {
    var bytes = Encoding.UTF8.GetBytes("Hello, OWIN!");
    var length = bytes.Length.ToString();

    var headers = env.["owin.ResponseHeaders"];
    headers.Add("Content-Type", new[] { "text/plain" });
    headers.Add("Content-Length", new[] { length });

    var stream = (Stream)env.["owin.ResponseBody"];
    return stream.WriteAsync(bytes, 0, bytes.Length);
});
```
For building the pipeline we need to create the idea of Middlewares. It can be achieved with the Chain Of Responsibility pattern.

The code above **AppFunc** is middleware and it can encapsulate the next element of the chain (which is middleware). And it calls the next one, repeating in the same way as the others, like a nested chain.

So, it can be implemented as Class and Function. But I will just show the Class sample;

```csharp
public class LoggingMiddleware{
    private AppFunc _next;
    
    public LoggingMiddleware(AppFunc next){
        this._next = next; 
    }
    
    public Task LogBefore(Environment env) { /**/ }
    public Task LogAfter(Environment env) { /**/ }
    public async Task Invoke(Environment env) {
        LogBefore(env);
        await _next(env)
        LogAfter(env);
    }
}
```
That was the middleware side.

Also has **IAppBuilder** interface for the pipeline side. Its main purpose is to provide the contract for configuring the middleware pipeline that handles HTTP requests and responses.

- Originally intended to provide the delegate signatures
- IAppBuilder was later added and left as the only interface

```csharp
public interface IAppBuilder
{
    IDictionary<string, object> Properties { get; }
    IAppBuilder Use(object middleware, params object[] args);
    object Build(Type returnType);
    IAppBuilder New();
}
```
As you can see, the OWIN solution has minimal dependency by simply relying on the FCL. These basic things that help OWIN to achieve its goal.

P.S. Microsoft implemented OWIN idea, its Katana, but this is another topic.

## Conclusion
OWIN is a specification that provides the rules for decoupling between web servers and web applications. Also, it helps to achieve modular architecture between web servers and applications. The idea behind it is used in many other web technology environments. OWIN is a powerful idea that helped to .NET community by providing an alternative to traditional IIS and ASP.NET (old) hosting models, addressing their limitations.

Stay tuned!