Professional Documents
Culture Documents
1 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
CPOL
The tools and architectural patterns we use to build and evolve web
applications have undergone dramatic change over the past few
years. Modern web application development is a fast-paced,
dynamic activity reliant to ever an greater degree on modular,
loosely-coupled application components, rapidly-evolving
frameworks, and shorter development cycles.
Historically, the ASP.NET ecosystem (including Web Forms, MVC,
Web Api, SignalR, and others) sat on top of System.Web, and was
tightly coupled to the underlying .NET framework as a whole.
Further, ASP.NET web applications have been reliant on Microsoft
Internet Information Services (IIS) to provide the hosting
environment necessary to run in production.
Image by Sunova Surfboards | Some Rights Reserved
27/10/2015 21:43
2 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
ASP.NET Web Api: Understanding OWIN/Katana Authentication/Authorization Part II: Models and Persistence
In the past two years, the ASP.NET team has been evolving the .NET web development ecosystem away from this approach, and
instead creating a growing set of pluggable components. Beginning with ASP.NET 4.5.1, we have seen the introduction of more
and more pluggable application components which are not dependent on System.Web, and which can be configured to run
outside the constraints of IIS using custom hosts.
My understanding is that ASP.NET 5 ("vNext") will be moving way, way further in this direction.
Understanding the relationship between the hosting process, the web server, and our application components is going to
become increasingly important as the ASP.NET ecosystem becomes more and more modular. More and more, this relationship,
and the pluggable architecture upon which our .NET web applications will depend, has been defined by the Open Web Interface
for .NET (OWIN) specification.
And we need to understand how it works in order to take full advantage of the evolving .NET Web Stack.
UPDATE 1/5/2015: ASP.NET 5 is indeed moving further in this direction. Katana itself will apparently be fully integrated into
ASP.NET 5. OWIN will be available through an interop, but greenfield projects will be best off using the integrated middleware
pipeline. The implementation details will be changing to a degree. However, most of what we discuss here will still apply, either
directly, or conceptually (thanks to Rick Anderson and the ASP.NET team for the clarification!).
We will examine the ASP.NET 5 middleware pipeline in an upcoming post.
OWIN Definitions
OWIN provides the following general definitions for software elements in an OWIN-based application:
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.
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.
Host The process an application and server execute inside of, primarily responsible for application startup. Some
Servers are also Hosts.
27/10/2015 21:43
3 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
In light of this, each middleware component needs to provide an AppFunc delegate to be called in order to do its own work in
the pipeline, and also needs to receive a reference to the next AppFunc delegate, to be called (in most cases) once the current
component has completed processing.
In other words, a middleware can be expressed with a signature which accepts an AppFunc delegate as an argument (which is
retained and called as the next process in the pipeline), and which returns an AppFunc Delegate (which is used to perform the
current middleware processing:
27/10/2015 21:43
4 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Func<AppFunc, AppFunc>
In code, this might look something like this:
What is Katana?
Katana is a set of open source components for building and hosting OWIN-based web applications, maintained by the Microsoft
Open Technologies Group.
Katana provides an implementation of the OWIN specification, and is in fact used in an increasing number of ASP.NET project
templates. Additionally, Katana provides a wide variety of ready-to-use middleware components, ready for use in an
OWIN-based application.
For our purposes, we will use some basic components from Katana to demonstrate and understand:
How an OWIN-based middleware pipeline is configured
How to construct a basic middleware component
How OWIN and the middleware pipeline fit into a web application generally
How all this comes together into the middleware pipeline, and the manner in which your application configures and interacts
with it can be confusing at first. For one thing, we are dealing with a lot of delegate functions and generic types. Also, there are
still some things happening behind the scenes that are not obvious at first.,
The best way to understand how OWIN, Katana, and the middleware pipeline works is, well, to jump in and mess about.
27/10/2015 21:43
5 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
System.IO;
27/10/2015 21:43
6 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Now, let's take a look at a few items of note here. First off, we have added an alias for the Application
Delegate, so that in our code, we can refer to Func<IDictionary<string, object> , Task> by the
name AppFunc.
Next, we have added a method to the Startup class, MyMiddleware(), which accepts an argument of type AppFunc
named next, and returns and AppFunc. If we look closely, we see that the anonymous function returned by the
MyMiddleware() method, when invoked by the host against an incoming HTTP request, will perform some basic processing
against the incoming request (actually, writing to the response body), and will then invoke the AppFunc next passed in as an
argument, passing to it the environment dictionary, and thereby continuing the pipeline processing of the request.
Bear in mind that the MyMiddleware() method simply returns the anonymous function to the caller, but does not invoke it.
The function will be added the to request processing pipeline, and will be invoked when an incoming HTTP request needs to be
processed.
Most importantly, let's take a look at the Startup class.
In the Katana implementation of the OWIN specification, the host will look for a startup entry point to build the middleware
pipeline in one of four ways (in order as listed below):
The Startup class is specified as a command line argument, or a type argument (where applicable) when the host in
initialized (usually when using OwinHost, or the Owin.Hosting API, which is what we did in our code above).
The host will look in the relevant app.Config or web.Config file for an appSettings entry with the key "owin:AppStartup"
The host will scan the loaded assemblies for the OwinStartup attribute and uses the type specified in the attribute.
If all of the preceding methods fail, then the host will use reflection and scan the loaded assemblies for a type named
Startup with a method with the name and signature void Configuration(IAppBuilder).
The Startup class must provide a public Configuration() method, as mentioned above, with the signature void
Configure(IAppBuilder app).
27/10/2015 21:43
7 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
And, if we open a web browser and navigate to our URL, we see the expected output:
Presto! We have created a bare-bones, self-hosted web application using only a console application, and a handful of small
Katana components.
More importantly, we have created our first OWIN middleware.
Now, let's see how the whole pipeline/chaining thing works.
27/10/2015 21:43
8 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Now, all we have done is create another middleware and add it to the pipeline by passing it to app.Use(),
similar to the first. However, if we run our application again, we see that both middlewares are executed:
Running the Application with Multiple Middlewares in the Pipeline:
Now, it would be easy to think that maybe both functions are just executing anyway, but let's see what happens when we
comment out the bit where we invoke the "next" AppFunc in our first middleware:
27/10/2015 21:43
9 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Refresh our browser, we see the second middleware never executed, even though is has been added to the
pipeline:
Next Middleware Fails if Next is not Invoked:
Clearly, if next is not invoked, the pipeline is short-circuited. Also, if we change the order in which we add the middlewares to the
pipeline, the processing order is affected:
Change the order Middlewares are added (and uncomment call to next):
public void Configuration(IAppBuilder app)
{
var middleware = new Func<AppFunc, AppFunc>(MyMiddleWare);
var otherMiddleware = new Func<AppFunc, AppFunc>(MyOtherMiddleWare);
// Swap the order here:
app.Use(otherMiddleware);
app.Use(middleware);
}
Refreshing the view in our browser, we should not be surprised:
27/10/2015 21:43
10 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Thus far we have implemented a very basic OWIN-based Processing pipeline, using the raw types expected by the OWIN
specification. Now let's see if we can make life a little easier, using some tools provided by Katana, and by laying some
abstraction on our middlewares to make them easier to think about.
OwinContext. We can use IOwinContext to access some of the information in the Environment Dictionary in a more
convenient, strongly typed manner. For example, we could modify our code like so:
IOwinResponse provide a large number of useful, strongly-typed abstractions which simplify our interaction with the
environment. These interfaces are, in fact, quite similar to the familiar HttpContext, HttpRequest, and
HttpResponse objects we are accustomed to using in a standard MVC or Web Api application.
27/10/2015 21:43
11 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
So far, we've taken the raw, bare-bones approach to creating middleware for our application, by using a method with the
signature Func<AppFunc, AppFunc> and pushing it into our pipeline. However, a more modular approach would be to
create our middleware are individual classes.
We can do this, so long as the class we create adheres to some specific requirements.
The class must have a constructor which accepts an argument of (wait for it) AppFunc, and must provide a method named
Invoke which accepts an argument of IDictionary<string,
To continue our trivial example, we can take our two methods, MyMiddleWare()and MyOtherMiddleware() and
create classes instead:
27/10/2015 21:43
12 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Once again, running our application, and refreshing the browser, we see everything still works as expected.
27/10/2015 21:43
13 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Modify the Extension Method to Accept and Pass the New Configuration Argument:
public static class AppBuilderExtensions
{
public static void UseMyMiddleware(this IAppBuilder app, string greetingOption)
{
app.Use<MyMiddlewareComponent>(greetingOption);
}
public static void UseMyOtherMiddleware(this IAppBuilder app)
{
app.Use<MyOtherMiddlewareComponent>();
}
}
And last, of course, we need to modify the code in Configuration() in the Startup class to pass in an acceptable
argument:
In our simplistic example here, we were able add a string argument to our middleware constructor, and
everything worked out just fine. More commonly though, middleware will likely require more configuration
options. Also, this does not represent a very modular design approach. Instead, we might be better off using a
configuration class, to be passed to the constructor instead.
27/10/2015 21:43
14 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
And finally, we now need to prepare our configuration during the Configuration() method of the
Startup class (which actually makes a lot of sense, no?):
Perform Middleware Configuration During Call to Configuration() Method:
public void Configuration(IAppBuilder app)
{
// Set up the configuration options:
var options = new MyMiddlewareConfigOptions("Greetings!", "John");
options.IncludeDate = true;
// Pass options along in call to extension method:
app.UseMyMiddleware(options);
app.UseMyOtherMiddleware();
}
Running the application, and refreshing the browser, we see the impact of our configuration options:
Refresh Browser to View Effect of Configuration Options:
27/10/2015 21:43
15 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Ok, we have just about exhausted the usefulness of these two example middleware components. Let's take a look at some (still
silly and contrived) mocked up components that represent something we might actually find in a pipeline.
Microsoft.Owin.
Add a Mock Authentication Middleware Class as a Separate Code File:
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
Owin;
Microsoft.Owin;
namespace KatanaConsole
{
// use an alias for the OWIN AppFunc:
using AppFunc = Func<IDictionary<string, object>, Task>;
public class SillyAuthenticationComponent
{
AppFunc _next;
public SillyAuthenticationComponent(AppFunc next)
{
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
// In the real world we would do REAL auth processing here...
var isAuthorized = context.Request.QueryString.Value == "john";
if(!isAuthorized)
{
context.Response.StatusCode = 401;
context.Response.ReasonPhrase = "Not Authorized";
// Send back a really silly error page:
await context.Response.WriteAsync(string.Format("<h1>Error {0}-{1}",
context.Response.StatusCode,
context.Response.ReasonPhrase));
}
else
{
// _next is only invoked is authentication succeeds:
context.Response.StatusCode = 200;
context.Response.ReasonPhrase = "OK";
await _next.Invoke(environment);
}
}
27/10/2015 21:43
16 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
}
}
In the above code, note that we totally fake an authorization request. Instead of grabbing an auth token from the request
header or some other secure way of doing things, we are cheating, and simply passing in a query string to check.
Also notice that if authorization fails, _next is never invoked. This matters in a moment.
Now let's add a hokey logging middleware:
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
Microsoft.Owin;
namespace KatanaConsole
{
// use an alias for the OWIN AppFunc:
using AppFunc = Func<IDictionary<string, object>, Task>;
public class SillyLoggingComponent
{
AppFunc _next;
public SillyLoggingComponent(AppFunc next)
{
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
// Pass everything up through the pipeline first:
await _next.Invoke(environment);
// Do the logging on the way out:
IOwinContext context = new OwinContext(environment);
Console.WriteLine("URI: {0} Status Code: {1}",
context.Request.Uri, context.Response.StatusCode);
}
}
}
Here, we are logging the incoming URI, and the status code of each request. Since we want to know the status code AFTER the
request has been processed, we are going to place this component first in the pipeline, but do no processing until after the call
to _next.Invoke() returns. In other words, we want to log status after all subsequent processing happens.
With this done, let's go ahead and add Extension methods for both of these components for ease of use with IAppBuilder:
27/10/2015 21:43
17 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Recall that the way we set up our Authentication middleware, the only valid login will be a URL with a query
string value of "john":
The "Authenticated User" Login URL:
http://localhost:8080/?john
So now, we can run our re-configured application and check out the refreshed view in the browser:
27/10/2015 21:43
18 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Looks like everything worked as expected. Now lets take a look at our console window, and see how our logging middleware
did:
Well THAT'S interesting even though everything seems to have worked, we are getting a 404 ("Not Found") status code.
This is because the last middleware in our pipeline is calling _next.Invoke() , but there is no AppFunc available to call. In
a real middleware, this would likely need some proper handling.
In our case, the MyMiddleWareComponent actually appears to be designed to be a final component in a chain (the one
writing to the response body and returning to the client), so we could actually place the work of the component after the call to
invoke _next, knowing that unless some really special circumstances arose, there will not likely be any additional components.
27/10/2015 21:43
19 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
_configOptions = configOptions;
}
public async Task Invoke(IDictionary<string, object> environment)
{
// If there is no next component, a 404 Not Found will be written as
// the response code here:
await _next.Invoke(environment);
IOwinContext context = new OwinContext(environment);
// Insert the _greeting into the display text:
await context.Response.WriteAsync(string.Format("<h1>{0}</h1>",
_configOptions.GetGreeting()));
// Update the response code to 200 OK:
context.Response.StatusCode = 200;
context.Response.ReasonPhrase = "OK";
}
}
If we run things again with our modified code, we should see the expected 200 OK response status in the console output.
Now, let's try reloading the browser with a different URI/query string:
If we type this new, "invalid" user URL into the address bar of the browser, we see our poor-man's Error page:
Load Browser with "Invalid" User URL:
We can also see that our logging middleware properly logged the invalid attempt out to the console:
27/10/2015 21:43
20 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
27/10/2015 21:43
21 of 25
using
using
using
using
using
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
System.Linq;
System.Text;
System.Threading.Tasks;
Owin;
Microsoft.Owin;
namespace SillyAuthentication
{
// use an alias for the OWIN AppFunc:
using AppFunc = Func<IDictionary<string, object>, Task>;
public class SillyAuthentication
{
AppFunc _next;
public SillyAuthentication(AppFunc next)
{
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
// In the real world we would do REAL auth processing here...
var isAuthorized = context.Request.QueryString.Value == "john";
if (!isAuthorized)
{
context.Response.StatusCode = 401;
context.Response.ReasonPhrase = "Not Authorized";
// Send back a really silly error page:
await context.Response.WriteAsync(string.Format("<h1>Error {0}-{1}",
context.Response.StatusCode,
context.Response.ReasonPhrase));
}
else
{
// _next is only invoked is authentication succeeds:
context.Response.StatusCode = 200;
context.Response.ReasonPhrase = "OK";
await _next.Invoke(environment);
}
}
}
}
Note in the above, that we have changed the name of the class from SillyAuthenticationComponent to simply
SillyAuthentication. Secondly, if we copies the code from the original project, we need to change the namespace from
KatanaConsole to SillyAuthentication.
Also, the way we set the alias for AppFunc must be specified for each code file where the alias will be used, so we need to do
that here as well.
Next, we will need to add a new AppBuilderExtensions class, so that when we reference our component within another
project, the extension method is there and ready to use:
27/10/2015 21:43
22 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
{
app.Use<SillyAuthentication>();
}
}
}
Obviously, since this assembly is specific to our SillyAuthentication component, we don't need the other extension
methods we defined in our original project.
We can do the same thing for our other components and we should have separate assemblies for the authentication
component, the logging component, and our MyMidddleware component. In each case, we will probably want to rename
the classes, dropping the "component" from each class name. Also, we need to use Manage Nuget Packages for Solution and
bring Microsoft.Owin into each project.
Make sure to specify the AppFunc alias in each file.
Finally, for the MyMiddleware project, we will make sure to bring the MyMiddlewareConfiguration into the project
as well.
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
System.IO;
27/10/2015 21:43
23 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
Why Do I Care?
In this post we have taken a look at how the OWIN/Katana pipeline works, seen some of the basics of how middleware is
created and added to the pipeline, and developed an understanding of how our application interacts with the server in an
OWIN-based environment.
Why do you care?
For one thing, more and more of the .NET web development ecosystem is moving in this direction. At present, ASP.NET Web Api
can be hosted directly in the OWIN/Katana pipeline (although in the template projects available in Visual Studio, the Web Api is
added to the ASP.NET/System.Web pipeline instead), and the ASP.NET Identity Framework IS added to the Katana pipeline.
My understanding is, going forward ASP.NET 5 ("vNext") is going to go all the way in this direction, with the various bits and
pieces we want to add to our project added as pipeline components.
UPDATE 1/5/2015: ASP.NET 5 is indeed moving further in this direction. Katana itself will apparently be fully integrated into
ASP.NET 5. OWIN will be available through an interop, but greenfield projects will be best off using the integrated middleware
pipeline. However, most of what we discuss here will still apply, either directly, or conceptually (thanks to Rick Anderson and the
ASP.NET team for the clarification!).
Understanding the hosting and server environment, and being able to dig down into the abstractions will allow us to better
leverage the tools at our disposal, and write better, learner, meaner applications.
Are we going to be writing a bunch of custom middleware components ourselves? Likely not. But understanding how the pieces
fit is important.
27/10/2015 21:43
24 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Share
About the Author
John Atten
Software Developer XIV Solutions
United States
My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things
technology and software development. I work mostly with C#, Javascript/Node.js, Various flavors of databases, and anything
else I find interesting. I am always looking for new information, and value your feedback (especially where I got something
wrong!)
27/10/2015 21:43
25 of 25
http://www.codeproject.com/Articles/864725/ASP-NET-Understandin...
with messages.
Selecione o idioma
27/10/2015 21:43