Aspnet Owin

download Aspnet Owin

of 25

description

AspNer Owin

Transcript of Aspnet Owin

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 1/27

    John Atten, 26 Jan 2015 CPOL

    ASP.NET: Understanding OWIN, Katana, and theMiddleware Pipeline

    The tools and architectural patterns we use to build and evolve web applications have undergone dramatic change over thepast few years. Modern web application development is a fastpaced, dynamic activity reliant to ever an greater degree onmodular, looselycoupled application components, rapidly

    The tools and architectural patterns we use to build and evolveweb applications have undergone dramatic change over thepast few years. Modern web application development is a fastpaced, dynamic activity reliant to ever an greater degree onmodular, looselycoupled application components, rapidlyevolving 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 awhole. Further, ASP.NET web applications have been reliant onMicrosoft Internet Information Services IIS to provide thehosting environment necessary to run in production.

    Image by Sunova Surfboards | Some Rights Reserved

    What is OWIN, and Why Do I Care?What is Katana?

    Console Application Example: Creating a Barebones Katana ApplicationKatana and the IAppBuilder InterfaceChaining Multiple MiddlewaresUsing Katana Abstractions: IOwinContextCreating Middleware Components as StandAlone ClassesAdd Custom Extensions for IAppBuilderAdding Middleware Configuration OptionsRequests, Responses, and ShortCircuiting the Middleware PipelineCreate MiddleWare Components as StandAlone AssembliesConsuming the StandAlone Components from the Sample ProjectASP.NET Web Api 2.2: Create a SelfHosted OWINBased Web Api from ScratchAdditional Resources and Items of Interest

    We expand upon the middleware concepts discussed here, and tie things together with ASP.NET Web API, in the next fewposts:

    ASP.NET Web Api 2.2: Create a SelfHosted OWINBased Web Api from ScratchASP.NET Web Api: Understanding OWIN/Katana Authentication/Authorization Part I: ConceptsASP.NETWebApi:UnderstandingOWIN/KatanaAuthentication/AuthorizationPartII:ModelsandPersistence

    In the past two years, the ASP.NET team has been evolving the .NET web development ecosystem away from this approach,

    5.00 34 votes

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 2/27

    and instead creating a growing set of pluggable components. Beginning with ASP.NET 4.5.1, we have seen the introductionof more and more pluggable application components which are not dependent on System.Web, and which can beconfigured 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 tobecome increasingly important as the ASP.NET ecosystem becomes more and more modular. More and more, thisrelationship, and the pluggable architecture upon which our .NET web applications will depend, has been defined by theOpen 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: $631(7LVLQGHHGPRYLQJIXUWKHULQWKLVGLUHFWLRQ.DWDQDLWVHOIZLOODSSDUHQWO\EHIXOO\LQWHJUDWHGLQWR$631(72:,1ZLOOEHDYDLODEOHWKURXJKDQLQWHURSEXWJUHHQILHOGSURMHFWVZLOOEHEHVWRIIXVLQJWKHLQWHJUDWHGPLGGOHZDUHSLSHOLQH7KHLPSOHPHQWDWLRQGHWDLOVZLOOEHFKDQJLQJWRDGHJUHH+RZHYHUPRVWRIZKDWZHGLVFXVVKHUHZLOOVWLOODSSO\HLWKHUGLUHFWO\RUFRQFHSWXDOO\WKDQNVWR5LFN$QGHUVRQDQGWKH$631(7WHDPIRUWKHFODULILFDWLRQ

    We will examine the ASP.NET 5 middleware pipeline in an upcoming post.

    What is OWIN, and Why Do I Care?

    OWIN the Open Web Interface for .NET is an opensource specification describing an abstraction layer between webservers and application components. The goal of the OWIN specification is to facilitate a simple, pluggable architecture for.NETbased Web applications and the servers upon which they rely, encouraging development of small, focused applicationcomponents known as "middlewares" in the OWIN parlance which can be assembled into a processing pipeline throughwhich the server can then route incoming HTTP requests.

    From the Owin.org About page:

    2:,1GHILQHVDVWDQGDUGLQWHUIDFHEHWZHHQ1(7ZHEVHUYHUVDQGZHEDSSOLFDWLRQV7KHJRDORIWKH2:,1LQWHUIDFHLVWRGHFRXSOHVHUYHUDQGDSSOLFDWLRQHQFRXUDJHWKHGHYHORSPHQWRIVLPSOHPRGXOHVIRU1(7ZHEGHYHORSPHQWDQGE\EHLQJDQRSHQVWDQGDUGVWLPXODWHWKHRSHQVRXUFHHFRV\VWHPRI1(7ZHEGHYHORSPHQWWRROV

    OWIN is a VSHFLILFDWLRQ, not an LPSOHPHQWDWLRQ. As such, OWIN describes a minimal set of types, and a single DSSOLFDWLRQGHOHJDWH through which interactions between an application component and the server will occur.

    Note that the OWIN specification is an open source community effort independent of Microsoft.

    OWIN Definitions

    OWIN provides the following general definitions for software elements in an OWINbased application:

    6HUYHU7KH+773VHUYHUWKDWGLUHFWO\FRPPXQLFDWHVZLWKWKHFOLHQWDQGWKHQXVHV2:,1VHPDQWLFVWRSURFHVVUHTXHVWV6HUYHUVPD\UHTXLUHDQDGDSWHUOD\HUWKDWFRQYHUWVWR2:,1VHPDQWLFV

    :HE)UDPHZRUN$VHOIFRQWDLQHGFRPSRQHQWRQWRSRI2:,1H[SRVLQJLWVRZQREMHFWPRGHORU$3,WKDWDSSOLFDWLRQVPD\XVHWRIDFLOLWDWHUHTXHVWSURFHVVLQJ:HE)UDPHZRUNVPD\UHTXLUHDQDGDSWHUOD\HUWKDWFRQYHUWVIURP2:,1VHPDQWLFV

    :HE$SSOLFDWLRQ$VSHFLILFDSSOLFDWLRQSRVVLEO\EXLOWRQWRSRID:HE)UDPHZRUNZKLFKLVUXQXVLQJ2:,1FRPSDWLEOH6HUYHUV

    0LGGOHZDUH3DVVWKURXJKFRPSRQHQWVWKDWIRUPDSLSHOLQHEHWZHHQDVHUYHUDQGDSSOLFDWLRQWRLQVSHFWURXWHRUPRGLI\UHTXHVWDQGUHVSRQVHPHVVDJHVIRUDVSHFLILFSXUSRVH

    +RVW7KHSURFHVVDQDSSOLFDWLRQDQGVHUYHUH[HFXWHLQVLGHRISULPDULO\UHVSRQVLEOHIRUDSSOLFDWLRQVWDUWXS6RPH6HUYHUVDUHDOVR+RVWV

    The OWIN Environment Dictionary

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 3/27

    The host in an OWINcompatible application provides an Environment Dictionary in the form of containing all of the relevant information about the request, response, andserver/host information. The OWIN specification defines a minimum set of keys and values which must be present in thedictionary. However, servers, host environments, middleware, and application code may add additional data, or modify thedata in the dictionary as a result of processing.

    The OWIN Application Delegate Function

    As mentioned above, OWIN also specifies a primary interface, the $SSOLFDWLRQ'HOHJDWH also known as $SS)XQF.Interactions between the server and application components occurs through calls to the $SS)XQF delegate.

    An $SSOLFDWLRQ'HOHJDWH function will take the Environment Dictionary as anargument, use the request/response information contained in the environment dictionary to perform whatever processingis required to meet its responsibilities, and return a when processing is complete.

    The Application Delegate Function Signature specified by OWIN:

    In our code, we will often use the alias for this delegate to improve readability:

    Alias the Application Delegate for use in code:

    The OWIN Middleware Pipeline

    In keeping with the above, individual application components middleware perform their processing duties when the delgate is called. However, in order to maintain the pipeline, each middleware component is also responsible forinvoking the next component in the chain or, intentionally NOT calling the next component and shortcircuiting the chain ifappropriate.

    In light of this, each middleware component needs to provide an delegate to be called in order to do its ownwork in the pipeline, and also needs to receive a reference to the next delegate, to be called in most cases oncethe current component has completed processing.

    In other words, a middleware can be expressed with a signature which accepts an delegate as an argumentwhich is retained and called as the next process in the pipeline, and which returns an Delegate which is usedto perform the current middleware processing:

    Middleware Delegate Signature:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 4/27

    In code, this might look something like this:

    Example Middleware as Function:

    We'll see how all this works shortly.

    What is Katana?

    Katana is a set of open source components for building and hosting OWINbased web applications, maintained by theMicrosoft Open Technologies Group.

    Katana provides an implementation of the OWIN specification, and is in fact used in an increasing number of ASP.NETproject templates. Additionally, Katana provides a wide variety of readytouse middleware components, ready for use in anOWINbased application.

    For our purposes, we will use some basic components from Katana to demonstrate and understand:

    How an OWINbased middleware pipeline is configuredHow to construct a basic middleware componentHow 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 andinteracts 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.

    Console Application Example: Creating a Barebones Katana Application

    An example of the simplicity available with an OWINbased application is the fact that we can create a simple Consoleapplication, pull in a few Nuget packages, and spin up a selfhosted web server. To get started, create a new consoleapplication in visual studio. Then, add the following Nuget packages using the Package Manager Console:

    Install Microsoft.Owin.Hosting via Nuget Package Manager Console:

    The package added a few library references to our project, notably ,, and of course, .

    Next, we need to add a means for our console application to listen for HTTP requests:

    Install Microsoft.Owin.Host.HttpListener via Nuget Package Manager Console:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 5/27

    With that, we have everything we need to put together a simple selfhosted web application.

    Most of the examples we examine in this post will be overly some might say "stupidly" simple, and let's bear in mind thatwe are focusing more on how basic middleware are constructed, and how the middleware pipeline works in general thanwe are on how to write specific middleware components, or how to use all of the Katana features. I stick with silly exampleshere so that we are focused on the core middleware structure, and how the pipeline works, and not on complex middlewareimplementation details.

    First, add the following code the the 3URJUDPFV file in your application:

    The basic KatanaConsole Application:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 6/27

    Now, let's take a look at a few items of note here. First off, we have added an alias for the ApplicationDelegate, so that in our code, we can refer to by thename .

    Next, we have added a method to the class, , which accepts an argument of type named , and returns and . If we look closely, we see that the anonymous function returned bythe method, when invoked by the host against an incoming HTTP request, will perform some basicprocessing against the incoming request actually, writing to the response body, and will then invoke the passed in as an argument, passing to it the environment dictionary, and thereby continuing the pipeline processing of therequest.

    Bear in mind that the method simply returns the anonymous function to the caller, but does notinvoke it. The function will be added the to request processing pipeline, and will be invoked when an incoming HTTPrequest needs to be processed.

    Most importantly, let's take a look at the class.

    In the Katana implementation of the OWIN specification, the host will look for a startup entry point to build the middlewarepipeline in one of four ways in order as listed below:

    The class is specified as a command line argument, or a type argument where applicable when the hostin initialized usually when using , or the API, which is what we did in our codeabove.The host will look in the relevant DSS&RQILJ or ZHE&RQILJ file for an DSS6HWWLQJV entry with the key"owin:AppStartup"The host will scan the loaded assemblies for the attribute and uses the type specified in theattribute.If all of the preceding methods fail, then the host will use reflection and scan the loaded assemblies for a typenamed with a method with the name and signature .

    The Startup class must provide a public method, as mentioned above, with the signature void.

    Katana and the IAppBuilder Interface

    The interface is NOT a part of the OWIN specification. It is, however, a required component for a Katanahost. The interface provides a core set of methods required to implement the OWIN standard, and servesas a base for additional extension methods for implementing middleware.

    When the Katana host initializes the class and calls , a concrete instance of is passed as the argument. We then use to configure and add the applicationmiddleware components we need for our application, assembling the pipeline through which incoming HTTP requests willbe processed.

    The most common way to add middleware is by passing components to the method. Middleware components willbe added to the pipeline in the order they are passed to . This is important to bear in mind as we configure ourpipeline, as this will determine the order in which processing is applied to incoming requests and in reverse, to outgoingresponses.

    In our code, we grab a reference to our middleware function by calling , and then add it to thepipeline be passing it to .

    Running the Application

    If we run the application, we se that our server has started:

    Console output from first run of the Application:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 7/27

    And, if we open a web browser and navigate to our URL, we see the expected output:

    Navigate to URL in Browser:

    Presto! We have created a barebones, selfhosted web application using only a console application, and a handful of smallKatana components.

    More importantly, we have created our first OWIN middleware.

    Now, let's see how the whole pipeline/chaining thing works.

    Chaining Multiple Middlewares

    Thus far, we have created an application with a single middleware component in the pipeline. While we properly included aparameter in our middleware function for a "next" to be invoke, there is nothing to work with at the moment.

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 8/27

    Let's create a second component to add to the pipeline, and see how that works. Add another method to the Startup classin our code below the method:

    Add another Middleware function to the Startup class:

    Next, update the method to add this new middleware:

    Add the New Middleware to the Processing Pipeline in the Configure Method:

    Now, all we have done is create another middleware and add it to the pipeline by passing it to, similar to the first. However, if we run our application again, we see that both middlewaresare executed:

    Running the Application with Multiple Middlewares in the Pipeline:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 9/27

    Now, it would be easy to think that maybe both functions are just executing anyway, but let's see what happens when wecomment out the bit where we invoke the "next" in our first middleware:

    Comment Out Call to Invoke Next AppFunc:

    Refresh our browser, we see the second middleware never executed, even though is has been added tothe pipeline:

    Next Middleware Fails if Next is not Invoked:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 10/27

    Clearly, if next is not invoked, the pipeline is shortcircuited. Also, if we change the order in which we add the middlewaresto the pipeline, the processing order is affected:

    Change the order Middlewares are added and uncomment call to next:

    Refreshing the view in our browser, we should not be surprised:

    Changing the Order in Which Middleware is Added to the Pipeline:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 11/27

    Thus far we have implemented a very basic OWINbased Processing pipeline, using the raw types expected by the OWINspecification. Now let's see if we can make life a little easier, using some tools provided by Katana, and by laying someabstraction on our middlewares to make them easier to think about.

    Using Katana Abstractions: IOwinContext

    In our previous example, we worked with the raw Environment Dictionary as specified by OWIN. This provides a flexible,lowlevel mechanism, but is less than handy when we want to work with stronglytyped objects, and perhaps raise ourabstractions up a level in our pipeline implementation code.

    Katana provides us with a handy interface, t, and a concrete wrapper for the Environment Dictionary,. We can use to access some of the information in the Environment Dictionary in a moreconvenient, strongly typed manner. For example, we could modify our code like so:

    Modify Middleware Code to use IOwingContext:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 12/27

    In fact, the object, and similar interfaces provided by Katana such as and provide a large number of useful, stronglytyped abstractions which simplify our interaction with theenvironment. These interfaces are, in fact, quite similar to the familiar , , and objects we are accustomed to using in a standard MVC or Web Api application.

    Creating Middleware Components as StandAlone Classes

    So far, we've taken the raw, barebones approach to creating middleware for our application, by using a method with thesignature and pushing it into our pipeline. However, a more modular approach would beto 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 , and must provide a methodnamed Invoke which accepts an argument of and returns .

    To continue our trivial example, we can take our two methods, and andcreate classes instead:

    Create StandAlone Middleware as Separate Classes:

    Note, we have pulled our methods out and refactored them into classes. Also, we havemodified our method on the class to use the overloaded method, whichallows us to specify the type which represents our middleware as a generic type argument.

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 13/27

    Once again, we can run our application asis, and all should work as expected.

    Add Custom Extensions for IAppBuilder

    Middleware implementations often utilize extension methods to extend the interface, making it easier forthe developer to add middleware into the pipeline.

    For example, we can add a static class for our extension methods like so:

    Add Extension Methods to IAppBuilder for Our Custom Middleware:

    Then we can update our method again, and we see that our new extension methods are available:

    Update Configuration to Use Middleware Extension Methods:

    Once again, running our application, and refreshing the browser, we see everything still works asexpected.

    Adding Middleware Configuration Options

    Often we want the ability to pass in some configuration options for our middleware as it is added to the pipeline. Forexample, suppose we wanted some control over the text to be displayed when is invoked. Let's setthings up so we can pass in the message to be displayed during the call to , instead of hardcoding itinto the middleware itself:

    Add a String Configuration Parameter to MyMiddleware:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 14/27

    Of course, now the compiler is telling you you need to also modify the extension method we use to add to the pipeline, because we need to provide for the new constructor argument:

    Modify the Extension Method to Accept and Pass the New Configuration Argument:

    And last, of course, we need to modify the code in in the class to pass in an acceptableargument:

    Modify the Configuration Method to Pass an Appropriate Configuration Argument:

    In our simplistic example here, we were able add a string argument to our middleware constructor, andeverything worked out just fine. More commonly though, middleware will likely require moreconfiguration options. Also, this does not represent a very modular design approach. Instead, we might bebetter off using a configuration class, to be passed to the constructor instead.

    Use Configuration Objects for Configuring Middleware

    To take our contrived example to the limit, let's rethink how we have implemented the configuration options for ourmiddleware. Instead of passing in an arbitrary string when we add the middleware to the pipeline, lets create aconfiguration class which will use some predefined elements to construct a message.

    First, let's create a very contrived configuration options class:

    Configuration Options Class for MyMiddleware:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 15/27

    Now, we will once again need to update our extension methods:

    Modify Extension Methods to Pass Configuration Options:

    And finally, we now need to prepare our configuration during the method of the class which actually makes a lot of sense, no?:

    Perform Middleware Configuration During Call to Configuration Method:

    Running the application, and refreshing the browser, we see the impact of our configuration options:

    Refresh Browser to View Effect of Configuration Options:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 16/27

    Ok, we have just about exhausted the usefulness of these two example middleware components. Let's take a look at somestill silly and contrived mocked up components that represent something we might actually find in a pipeline.

    Create Mock Components for Logging, and Authentication

    As before, we are going to use some overly simple, contrived examples here. Katana actually provides for the addition ofboth Logging and Authentication components, and we aren't going to get bogged down in the complexities of writingcode to actually perform either of these functions beyond mocking their effects on pipeline flow. Each of those topics couldand probably will be a post unto itself.

    For now, let's add two new classes to our project. This time, though, let's add these as individual class files. This means wewill need to specify our alias in each class, as well as make sure the statements at the top of the fileinclude .

    Add a Mock Authentication Middleware Class as a Separate Code File:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 17/27

    In the above code, note that we totally fake an authorization request. Instead of grabbing an auth token from the requestheader 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, is never invoked. This matters in a moment.

    Now let's add a hokey logging middleware:

    Add a Mock Logging Middleware Class as a Separate Code File:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 18/27

    Here, we are logging the incoming URI, and the status code of each request. Since we want to know the status code AFTERthe request has been processed, we are going to place this component first in the pipeline, but do no processing until afterthe call to 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:

    Add Extension Methods for Auth and Logging Components:

    Now let's see how we might use these examples in modeling some "realworld" application behavior.

    Requests, Responses, and ShortCircuiting the Middleware Pipeline

    Recall our diagram of the middleware pipeline. We have a basic idea of how the request/response flow is supposed tooccur under normal circumstances. Let's use our two new middlewares, and reconfigure our application somewhat.

    First, we want to log the URL for each incoming request, and the status code of the response for each. Since we can't knowthe final status code until all of the pipeline processing has completed, we will put this middleware in the pipeline first. inother words, the logging middleware will be the first component to see each incoming request, and the last component tosee the outgoing repose.

    Next, we will add our Authentication component. We want to test authentication early in the pipeline, and preventunauthorized users from proceeding any further than necessary into our application.

    Finally, we will add our component, which display a helpful greeting in the browser window.

    We set all this up by modifying the method of the class as follows:

    Configure Application with Mock Logging and Authentication Middleware:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 19/27

    Recall that the way we set up our Authentication middleware, the only valid login will be a URL with aquery string value of "john":

    The "Authenticated User" Login URL:

    So now, we can run our reconfigured application and check out the refreshed view in the browser:

    Browser View with "Authenticated" Request:

    Looks like everything worked as expected. Now lets take a look at our console window, and see how our loggingmiddleware did:

    Console Output from Logging Middleware:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 20/27

    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 , but there is no available tocall. In a real middleware, this would likely need some proper handling.

    In our case, the actually appears to be designed to be a final component in a chain theone writing to the response body and returning to the client, so we could actually place the work of the component afterthe call to invoke , knowing that unless some really special circumstances arose, there will not likely be anyadditional components.

    Modify MyMiddleWareComponent to process after call to next:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 21/27

    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:

    An "Invalid" User URL:

    If we type this new, "invalid" user URL into the address bar of the browser, we see our poorman's Errorpage:

    Load Browser with "Invalid" User URL:

    We can also see that our logging middleware properly logged the invalid attempt out to the console:

    Console Output after "Invalid" login:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 22/27

    So what happened here in terms of our pipeline?

    As you may have reasoned, the intentionally shortcircuited the pipeline, by notinvoking the next component in the chain once use authentication failed. In this case, our pipeline flow looked somethinglike this instead of the previous diagram:

    Flow in the ShortCircuited Pipeline Due to Failed Authentication:

    Create MiddleWare Components as StandAlone Assemblies

    Unlike most of what we have done here, most of the time, OWIN middleware would tend to be composed as a standaloneassembly in its own class library. Most likely, the middleware itself will take some dependencies on other libraries, but itwould not tend to be part of the application assembly itself.

    To carry our most recent examples to their logical conclusion, we might extract each of our middleware components into itsown project, which, when ready for deployment, we might even host on Nuget as packages to be added to client projects.

    Looking at our middleware as an example, let's add a new project to our solution, named"SillyAuthentication." The project type should be "Class Library."

    Once we have done that, we can use 0DQDJH1XJHW3DFNDJHVIRU6ROXWLRQ to add the package to ournew class library.

    Now, we want to add two classes to the project. First, add the class itself:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 23/27

    Add the SillyAuthentication Class to the New Project:

    Note in the above, that we have changed the name of the class from SillyAuthenticationComponent to simply. Secondly, if we copies the code from the original project, we need to change the namespacefrom to S.

    Also, the way we set the alias for must be specified for each code file where the alias will be used, so we need todo that here as well.

    Next, we will need to add a new class, so that when we reference our component withinanother project, the extension method is there and ready to use:

    Add a new AppBuilderExtensions Class to the new Project:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 24/27

    Obviously, since this assembly is specific to our component, we don't need the otherextension 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 authenticationcomponent, the logging component, and our component. In each case, we will probably want torename the classes, dropping the "component" from each class name. Also, we need to use 0DQDJH1XJHW3DFNDJHVIRU6ROXWLRQ and bring into each project.

    Make sure to specify the alias in each file.

    Finally, for the project, we will make sure to bring the into theproject as well.

    Consuming the StandAlone Components from the Sample Project

    Now, we can remove the class from our example project, as well as delete theextension method we created related to the class.

    If we go to 6ROXWLRQ([SORUHU !3URMHFW'HSHQGHQFLHV and indicate that depends all three of our newclass library assemblies, and then also add a reference to each assembly using 5HIHUHQFHV !$GG5HIHUHQFH, we are ready toclean up and simplify our 3URMHFWFV file.

    At this point, we can ditch all of the previous middleware class files we were using within the projectitself. All we need is our main method, and our class, like so:

    Simplified KatanaSamples Project:

  • 11/12/2015 ASP.NET:UnderstandingOWIN,Katana,andtheMiddlewarePipelineCodeProject

    http://www.codeproject.com/Articles/864725/ASPNETUnderstandingOWINKatanaandtheMiddlewa?display=Print 25/27

    If we have done everything correctly, and didn't miss a namespace change or anything like that, our application should run exactly as before. However, this time, we have pulled in our custom middleware as references, whichcould just as easily come from Nuget.

    In fact, the code in our Startup class may look fairly familiar to you. If you take a look at the Startup.auth.cs file from theWeb Api project template, you will see similar goings on, as ASP.NET Identity components are added to the OWIN pipeline.

    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 iscreated and added to the pipeline, and developed an understanding of how our application interacts with the server in anOWINbased 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.NETWeb 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 theKatana pipeline.

    My understanding is, going forward ASP.NET 5 "vNext" is going to go all the way in this direction, with the various bits andpieces we want to add to our project added as pipeline components.

    UPDATE 1/5/2015: $631(7LVLQGHHGPRYLQJIXUWKHULQWKLVGLUHFWLRQ.DWDQDLWVHOIZLOODSSDUHQWO\EHIXOO\LQWHJUDWHGLQWR$631(72:,1ZLOOEHDYDLODEOHWKURXJKDQLQWHURSEXWJUHHQILHOGSURMHFWVZLOOEHEHVWRIIXVLQJWKHLQWHJUDWHGPLGGOHZDUHSLSHOLQH+RZHYHUPRVWRIZKDWZHGLVFXVVKHUHZLOOVWLOODSSO\HLWKHUGLUHFWO\RUFRQFHSWXDOO\WKDQNVWR5LFN$QGHUVRQDQGWKH$631(7WHDPIRUWKHFODULILFDWLRQ

    Understanding the hosting and server environment, and being able to dig down into the abstractions will allow us to betterleverage 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 thepieces fit is important.

    Additional Resources and Items of Interest

    Source Code on GithubThe Owin Project Home PageThe Owin SpecificationThe Katana Project on CodeplexASP.NET Web Api 2.2: Create a SelfHosted OWINBased Web Api from ScratchASP.NETWebApi:UnderstandingOWIN/KatanaAuthentication/AuthorizationPartII:ModelsandPersistenceASP.NET Identity 2.0: Introduction to Working with Identity 2.0 and Web API 2.2