[ASP.NET Core MVC Pipeline] Routing Middleware – Route Handler

Let’s move on with our series about the Core MVC Pipeline. What is the next step? Last time we learned how to point a request to a specific Router, and what if we need to handle a route in a custom way? Let’s create our custom Route Handler.

Middleware Pipeline
Middleware Pipeline

As we can see, the Route Handler is the last step inside our Routing Middleware and, as long as the request matches any of the routes, is also the last step inside the Middleware Pipeline, we are almost ready to move on to the next phase on the Core MVC Pipeline.

But what exactly does the Route Handler do? Let’s think functionally:

  1. Our Web Server received a request and, since it is a valid request, passed it to our application.
  2. Our application passed the request to our Middleware pipeline which running the request through every middleware until one of them decides to end the request.
  3. The request went through a lot of processes and reached our Routing Middleware.
  4. Our routing middleware will pass the request to our Router who will see if this request matches any known route. If it doesn’t, the middleware will pass the request to the next middleware, or initiate the response.

But what if the request matches any known route? What is next? That is where our Route Handler gets to do its magic!

The Route Handler is the component that defines what to do with the Request that matches a Route on our system. The default implementation for this component is the MvcRouteHandler, which usually handle every single request accepted by the Router, but now we are going to implement our own Route Handler.

Let's Code
Let’s Code

The Code

This component suffered a great deal of changes in the way it is structured on the Full .NET Framework in comparison with the .NET Core implementation.

To implement our Route Handler we are simply going to need a RequestDelegate. This request delegate will contain all the logic that must be executed against a matched route and create a response.

The code for this example will be very simple, as this is a very specialized component, and I don’t see it getting overriding frequently.

It is this simple! In this example any request matched and sent to our RouteHandler will redirect the user to this Blog 🙂 The object “c” is a HttpContext object, so anything that can be done with a request/response flow can be done in the RouteHandler as well.

Now we only have to hook up our RouteHandler on the Routing Middleware:

In the case (line 3) we created a Route that will match ANY request in which the URI starts with “blog/” and send it to our custom router, which will redirect the request.

And that is all there is for a simple custom router 🙂
There is of course other ways to implement Route Handlers but this should be more than enough for the very specific cases where this is necessary.

This wraps up our talk about the Middleware part of the MVC Pipeline! In the next post we start the talk on the Controller Initialization!

See you next time 🙂

That's All Folks
That’s All Folks


Surviving Success: Performance Tuning Under Pressure

You are part of a team responsible for an awesome application that is facing a great and sudden success! Awesome! But success will also, usually, expose some problems with your application that you are not prepared for… And now you are expected to fix a plane that is already on flight! How the hell are you supposed to do that?

I actually stole the title from this post from the name of the interesting video that I would like to share with you that is all about how to deal with this kinds of “success-related problems”.

Slow Down to Move Fast

Source: MS Build 2017

The Fallacy of Premature Optimization

I guess most of the professionals working on the software industry have already heard the following quote about optimization.

Premature optimization is the root of all evil.

This quote was popularized by Donald E. Knuth on his paper Structured Programming with go to statements, what most of us ignore is that the quote, in his most acknowledged form was taken out of the context. A more complete quote goes like this:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
Yet we should not pass up our opportunities in that critical 3%.

A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code.

As you can see, in a more complete context, the quote has quite a different perspective from ignoring the opportunity of optimizing your code prematurely.

You can, and you should, identify the 3% of your application that is really the critical path for your users, and the optimization of this part of the code should never be ignored, as it can cause you big problems at some point in the future.

Application performance is a subject that has been ignored for a few years with the increase of computational power, but now we are in a moment where users and systems demand the best possible performance from your application, so they can also deliver their results.

It is, of course, you option to identify this 3% as soon as you can, or to let your users find it for you. 🙂

Sources: Surviving Success

Favor Composition Over Inheritance Part 2 | Source: Coding Delight

And here is the second part of the article

Yesterday I wrote part one of my two-part series on why we should favor the technique of composition over inheritance. I began by looking at how a purely inheritance-based model quickly becomes unworkable as the properties and methods of base classes often lead to an inflexible design. Today, by contrast, I will look at solving the same problem by the use of composition. Specifically, we will look at how using interfaces for composition in C# allows for a highly flexible design.

The problem posed yesterday was to model the behavior of a car when a driver applies changes to it. I want to be able to track the angle of the wheels and the speed at which the wheels have been turned by the engine. The first car to model is the Toyota Corolla.

Yesterday, the first class that was designed was the BaseCar class, which contained a number of abstract methods which defined our behavior. It also contained our wheels. Today, instead, I am going to look at the behaviors of the car. It seems to me that there are two separate behaviors which are independent of each other. There is steering and there is driving (or accelerating). These behaviors will form the basis for our interface design. A car also has a manufacturer, so we will create an interface for that too.

There are a couple of ways that we could look at designing the car interface. We could say that an ICar inherits from both ISteering and IDriving, but instead I think we should say that an ICar has both an ISteering and IDriving. This seems to make the most sense.

Already we can see that simply by thinking about the components and how they logically relate to each other, we have created a different design from before. The interfaces help us think more abstractly than base classes would otherwise had. Now that we have designed our interfaces (and the astute reader might have noticed that the Wheel class has now become an IWheel interface too, though defining either is beyond the scope of these articles) we can get started on defining the functionality of our classes.

First we will create a TwoWheelDrive class which implements the IDriving interface.

Immediately it can be seen that this class can be used for both types of two-wheel drive car – front or rear. All we will have to do is pass either the front or rear wheels to it. Next up we’ll implement the two-wheel steering functionality in much the same way. Note that in this case, the steering class has to be a “front” steering class or a “rear” steering class, as each type of steering requires the wheels to turn in opposite directions to achieve the same outcome for the driver.

And next, my Toyota manufacturer class. I’ve implemented it as a singleton because that will be sufficient for this problem.

Finally, I can create my ToyotaCorolla class.

Now when the customer comes along and asks for the rear wheel drive sports edition, I can create the following class for them.

In fact, it is at this point that you can quite easily see that the only difference between ToyotaCorollas lies in the parameters that are passed into the driving constructor. A pattern is emerging. We now have the ability to do away entirely with our ToyotaCorolla class. The only difference is in our constructor parameters. What I can do instead is refactor my code and use constructor parameters to define our classes.

So as you can see, by using composition we have created a much more flexible design. We can reuse the bits that make sense to be reused and ignore the bits that don’t. The interfaces have helped us think abstractly and separated out how the objects relate to each other from how the objects work. We can use a car without knowing how the steering is implemented or whether it is a front, rear or four-wheel drive. We no longer have a complicated object hierarchy and adding new car designs takes a little effort. When it comes time to design a car with four-wheel drive, all we need to do is create a four-wheel drive class and a factory method.

Far too many professional developers think in an “is-a” mindset when they want to reuse code. I hope that I have sufficiently demonstrated that composition helps us reuse code far more efficiently and with a lot less complexity than using inheritance. As always, leave a comment, I would love to hear your feedback!

I am taking two weeks holiday, after which I will be (hopefully) blogging on a regular basis.


Source: Favor Composition Over Inheritance part 2 | Coding Delight

[ASP.NET Core MVC Pipeline] Routing Middleware – Custom IRouter

What if you want to add some custom logic to the routing system?

There are two main components where we can inject our code to bend some rules on the framework. The first one is the IRouter.

Middleware Pipeline - Routing
Middleware Pipeline

In our flow the IRouter is represented by the “Matching to Route Entry” box and that is what it is. The role of the IRouter in the Routing system is to match something on a request, usually on the URI, and point it to the right IRouteHandler. We are going to learn more about the RouteHandler component in a future post.

Why would I do that?

As previously said, the role of the IRouter in the pipeline is to evaluate the request and pass it to the IRouteHandler that is the best fit, but what might be mentioned is that you can also use the IRouter to make modifications to the incoming request. In this way, whenever you have a request that matches a certain criteria you can add, remove or edit some information and let the default RouteHandler do the rest.

In my experience, that is the most common case. I don’t see complete custom implementation of the Routing system so frequently.

The Basics

A bit different from the custom middleware, which is entirely implemented through conventions, the custom Router must implement an Interface called IRouter. This interface is quite simple:

The first method, GetVirtualPath, is used internally by the framework to generate urls based on this route in methods like the HTML.ActionLink one, the second method, RouteAsync, is where our logic will really reside.

Our class should start with something like this:

Routing our Requests

The concept behind the RouteAsync method is quite simple and straightforward, we do all the checking necessary to see if the provided route matches our IRouter context and, if it does, we execute the needed logic and inform the Routing middleware that the request has been handled.

We are doing the checking part on the if statement where we analyze if the request comes from a Mobile User-Agent (there are certainly better and more secure ways to do this but it is enough for the purpose of the demonstration) and if our Router finds that the request comes from such an agent, we apply some logic to change the controller and action values in our RouteData, therefore ensuring that our request will be redirected to the right Action.

If everything works as expected, then we send our modified context to the Default RouteHandler, and let it process it. The RouteHandler will set the value for the Handler property in our context, and it will let the framework know that the request has been Handled by our Router and no longer need to be processed by other Routers.

Hooking up to the Routing Middleware

Now we have a nice and functional Custom Router but if you run the application you will see that it is never touched by your request and that is because we never hooked our Router to the Routing Middleware.

The Routing Middleware has a stack of Routers that it will use to try and match a request, hence we need to add our Custom Router to this Stack. Let’s do it.

Now we add a new Router to the Routes collection and we passed the Default Handler, which will be used by our Routing flow.

And that is all we have to do to make our Router capture every request that comes from a mobile User-Agent and redirect them to specific controllers/actions.

To be completely honest, creating a custom Router will usually be a bit of an overkill as you can achieve most of the desired behaviors through the usage of easier components on the pipeline (including the middleware), but I think that is important to go through all the major components that we can customize.

What do you think? Sounds like something that you can use in your application?

Thanks for Reading! Tot ziens 🙂

MVC Pipeline Series

[ASP.NET Core MVC Pipeline] Middleware Pipeline

Let’s play with the Middleware Pipeline 🙂

Do you guys remember the flow that I showed you in the first post? No? Let’s revisit it:

The ASP.NET Core MVC Pipeline
The ASP.NET Core MVC Pipeline

So, what do we want to do here is to start from the beginning and in this post we are going to focus on the Blue part of the flow, the Middleware Pipeline:

Middleware Pipeline
Middleware Pipeline

What is a Middleware?

So, what is a middleware in the context of the Core MVC Pipeline, and why should we care about it?

Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline.

Hmmm… so each middleware is actually a piece of code, which follow some patterns, that we can ‘pile’ forming what we call a pipeline. Each of those pieces of code can (and should) implement its own logic and, that is the most interesting part, can decide whether or not to pass on a request! Because of that, each middleware is empowered to end an HTTP request and ignore every other middleware after if it decides to. Let me draw it for you:


Middleware Pipeline
Middleware Pipeline

In the example on the left, the request pass through all the middleware in the Pipeline and finally gets answered by the Routing Middleware.

In the example on the right, the request is cut short by a custom middleware that send the response itself rather than pass it along to next one.

A couple of important things to notice:

  • A middleware can execute successfully its function and still pass the request to next middleware, therefore allowing for more changes before sending the response.
  • The routing middleware is certainly an important one but he is not vital on the middleware pipeline. It is vital to the MVC Framework, but you could have a perfectly working application without the routing middleware.

Our first Middleware

The sequence of middleware is defined on the Configure method of the Startup.cs class.

Each of the “Use…” methods define a middleware. Let’s inject our own super simple middleware on the stack:

In this case we are defining that only the requests sent with the HTTP method GET are going to be pass on to the Routing Middleware. Other HTTP methods will be answered directly by our middleware and will never reach the Routing system. Notice that we defined our middleware inline, inside the Configure method and that is not a good practice because it worsen readability and break the Single Responsibility principle.

Pretty simple, ahn? Let’s get into some details.

Order Matters

Keep it in mind, the order in which your middleware is set up inside the Configure method matters! It matters because this is the order in which they are going to be executed when a request is received. In our example our custom middleware would never be hit if the user requests an existing static resource (like an image, or a JS file) because the UseStaticFiles middleware would have handle the request and sent a response to the user shortcutting the request.

Before AND After the next Middleware

We can see in our example that the execution of the next middleware in the pipeline is represented by a call to the next() delegate, and that means that we can execute some logic before and after the next delegate execution.

Use, Run or Map

Every middleware must run using one those three methods that define a specific behavior for the middleware.


First of all, the most common method, the ‘Use…‘. This method is the one that allows our middleware to receive a request, process it and, if necessary, pass it on to the next middleware on the pipeline.

Use(IApplicationBuilder, Func<HttpContext, Func, Task>)

We receive a delegate with an HTTPContext with all the details available about the request and another delegate, which is actually the call to the next middleware. As a result we can call the next middleware in the pipeline whenever we want or not even call it, if our logic says it is not necessary.


Then we have the ‘Run…‘ method and this method allows us to define a middleware that will always end the execution, simply because it has no knowledge of a next middleware in the pipeline.

Run(IApplicationBuilder, RequestDelegate)

In this case, the only thing we receive is the delegate with the custom logic of our own middleware.

Map & MapWhen

And then we have the ‘Map…‘ method which, as the name implies, allows us to map a request to a middleware depending on the Path of the request.

Map is a little bit different from the previous methods in the sense that you only map the request to a middleware, but you are still going to need to set an ‘Use…‘ or ‘Run…‘ method to actually execute our logic.

Map(IApplicationBuilder, PathString, Action)

So the Map method actually pass on an instance of the IApplicationBuilder interface! Which allows us to define a new middleware depending on the mapped request.

The Map method also has a variant called MapWhen that allows us to map the middleware against some condition on the HttpContext.

So, those four methods are supposed to give us all the flexibility that we need to create our middleware.

I think it is possible to notice that creating a middleware inline is not a great idea, right? It gets messy really quick and we don’t want that. Let’s start creating a real Middleware in a more decent way.

Creating our Custom Middleware

First of all we need to do is to create a new class and, to do that, we are going to follow some simple conventions. Our Middleware’s class and filename must end with the word ‘Middleware’:

This code, by itself, is already a working middleware. It won’t do anything, except calling the next middleware, but it will work. 🙂

Now I expect you to be asking “Where is the Base Class?”, “You forgot to implement the interface?” or “Where are the overridden methods?” and believe, I asked myself these exact same questions. The answer is simple, the framework will understand and use our Middleware based on the conventions we followed:

  • The Middleware must have a Constructor that accepts one RequestDelegate
  • The Middleware must have a public Method that receives an HttpContext as parameter and returns a Task type.

Pretty straightforward, right?

Let’s implement some logic to our Middleware. Worth mentioning that there should be better ways to implement what we are doing here, but for the purpose of the Post Series, it should be enough.

Basically what our middleware is doing is making sure that only requests with the “GET” method ever reach the next middleware and if any other method is used than the request will be shortcut.

Looks much better than having all this code inline right? But we are not ready yet!

Hookup with the Middleware Pipeline!

While this is a working code for a middleware we haven’t hooked this up to our pipeline. Let’s do this now. Back to our Startup.cs Class, in our configure method, we want our new middleware to be added like this:

Looking really good now, isn’t it? Let’s make look more like the rest of the middleware pipeline by creating one extension method for our middleware.

And now we can set up our Middleware like this:

And that is it! We have a custom middleware setup and working. Our pipeline now should work like this:

Middleware Samples
Middleware Samples

And that is it for the first post of the Core MVC Pipeline. What do you think? Can you imagine some scenarios where changing the Middleware Pipeline would be useful for your application?

On the next post we will start talking about the Routing Middleware, where we can introduce some logic to change the Routing rules 🙂

Tot ziens!


The ASP.NET Core MVC Pipeline

Hallo Iedereen 🙂
I decided to start a series of posts about custom components for the ASP.NET Core MVC Pipeline.

Most of you should know by now that ASP.NET Core was mostly redesigned to be more modular, extensible and to deal with the ‘platform agnostic’ nature of the new framework. This redesign also allows us to customize the way every request is processed, adding custom components in each step of the pipeline.

The ASP.NET Core MVC Pipeline

The ASP.NET Core MVC Pipeline
The ASP.NET Core MVC Pipeline

The idea is to have one post for each of the small blocks on the pipeline, precisely because it is possible to hook up your custom code in any of those points.

I’ll start by providing a brief overview of which is the role of each block on the pipeline:

Middleware Pipeline

Middleware Pipeline
Middleware Pipeline

The middleware pipeline is the entry point for each request in an HTTP Request, it is basically a stack of components that can execute some logic and decide whether to pass the request to the next middleware, or to send the response back to the client.

Routing Middleware

The routing middleware is just one of many that can be used by the ASP.NET Core but is of major importance to the Core MVC Pipeline. The reason for this it that this is the Middleware that ‘captures’ an incoming request and really starts the MVC Pipeline. If an incoming request url does not match any registered Route the request is passed onward to the next Middleware, ignoring the MVC Pipeline, but when the request url matches a known route, that is when the MVC Pipeline really begins.

Controller Initialization

Controller Initialization
Controller Initialization

Once a route is found by the Routing middleware, the next step is to find a controller that matches the route and instantiate it. The process of finding the best suitable Controller and Action for a Route can also be customized.

Action Execution

Action Execution
Action Execution

Now we are in the core of what really is the MVC pattern. The Action Execution is the process that will really process the incoming request and, after that, generate a Result. This is also the process where we can hook up most of our components.

Model Binding

One of the greatest features on the MVC Framework is the ability to bind request data to POCO Objects. I’ll try to explain a bit about how the standard Models Binders work, and how you can create your own Model Binder.


Filters are components that can be injected at many stages of the Action Execution and that will allow us to define behaviors that we want in our Actions, but that are not necessarily part of the LOB Logic.

Action Result

Finally, the action result is the last step of the Action Execution, and it involves basically to create a ‘Result’ type that will be processed by the Result Execution.

Result Execution

Result Execution
Result Execution

And the last step in the Core MVC Pipeline has arrived! Here is where our ‘Result’ will be analysed and processed accordingly. Here we can also inject some filters before and after our processing, allowing us to change the way the result will be processed.

Where do we start?

From the beginning! Of course 🙂 We will start creating a Custom Middleware that will be executed before the Routing Middleware.

The first post will be up very soon!

Tot ziens! (And I just spent all my Dutch in this post)