Friday, 9 March 2018

Asp.Net Core Pipeline

I've been playing around with Asp.Net Core 2 for a while and I pretty like it. Following the examples you can start your application with a few lines of code, as seen here, but what these lines are doing is a real lot and I wanted to get a better view of what's really going on.

In the end we can think of any asp.net core application (the .dll or .exe that we end up with) as a selfcontained web application made up of 3 main components:

  • A Web Server that takes care of receiving http requests and sending http responses
  • "Our application itself" (our controllers and so on) that processes that request and generates a response.
  • The framework code that communicates both components. The communication between these 2 components involves a Request Pipeline where different middlewares are hooked (think of these middlewares as equivalents to HttpHandlers in classic ASP.NET). MVC is one of those middlewares (Websockets is another possible middleware).

Asp.Net core comes with 2 web server components, the multiplatform Kestrel and the Windows only http.sys, but you can implement your own. Reading this excellent post about that, has quite helped me to better understand the different classes involved.

First of all we have an IWebHost. This IWebHost hosts the whole application and is its starting point (IWebHost.Run). We have to tell the WebHost what Web Server to use. We usually do this via the IWebHostBuilder UseKestrel or UseHttpSys extension methods. From the linked article this seems to come down to adding an IServer implementation to the Services collection (the default IOC container). The IWebHost will take care of calling the IServer.Start method, passing to it an IHttpApplication. Then the Web server will be calling IHttpApplication.ProcessRequestAsync with an HttpContext to process requests. What comes to mind is that this ProcessRequestAsync should be starting the processing in the chain of middlewares.

We have set up the chain of middlewares in our Startup.Configure method. This method receives an IApplicationBuilder where we invoke different Use methods to add middlewares. The part that was confusing me a bit is that IHttpApplicationBuilder.Build does not return an IHttpApplication, but a RequestDelegate. This RequestDelegate represents the Request pipeline with all its middlewares. So the IHttpApplication is the glue between the IServer and the RequestDelegate. When trying to figure out this I came across this excellent article that so well describes what I have been trying to explain in this post :-)

No comments:

Post a Comment