This is the third article in the series of articles on OWIN and Katana.
- Basics of OWIN and Katana
- OWIN middleware-ASP.NET integrated Pipeline extensions in Katana
In the previous article of this series we discussed the ASP.NET integrated pipeline and HttpModule. How to add your custom OWIN middleware component? In this article we'll be learning about the various stages of ASP.NET Integrated Pipeline and how to register and run your OMC at a specific stage.
The following is the list of various stages available in the Katana that act as an OWIN middleware:
- public enum PipelineStage
- {
- Authenticate = 0,
- PostAuthenticate = 1,
- Authorize = 2,
- PostAuthorize = 3,
- ResolveCache = 4,
- PostResolveCache = 5,
- MapHandler = 6,
- PostMapHandler = 7,
- AcquireState = 8,
- PostAcquireState = 9,
- PreHandlerExecute = 10,
- }
Now if you want to run your code at a specific stage then you just need to register your OMC with the stage. This can be done using StageMarkers in OWIN. So let's create or use our previous OMC and run it at a specific event. In this demo let's use the stage of Authentication and run our OMC during the Authroization stage in the ASP.NET Pipeline.
- using AppFunc = Func<IDictionary<string, object>, Task>;
- using Microsoft.Owin;
-
- public class Startup
- {
-
- public void Configuration(IAppBuilder builder)
- {
-
- builder.Use(new Func<AppFunc, AppFunc>(ignoredNextApp => (AppFunc)Invoke));
-
- builder.UseStageMarker(PipelineStage.Authenticate);
- }
-
- public Task Invoke(IDictionary<string, object> environment)
- {
- string responseText = "Hello World";
-
- byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);
-
- Stream responseStream = (Stream)environment["owin.ResponseBody"];
- IDictionary<string, string[]> responseHeaders =
- (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
- responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
- responseHeaders["Content-Type"] = new string[] { "text/plain" };
- return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);
- }
- }
Similarly you can something of any of the stages listed above and customize the ASP.NET pipeline to process your request or response.
In our next article we'll be talking about the self-host OWIN process. Say no to System.web and run your web request on an individual server without the boundaries of a platform or a host/server.