[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)


Favor Composition Over Inheritance part 1 | Source: Coding Delight

I have been discussing “Composition over Inheritance” with my teammates a lot on the last few weeks, and I really love to learn this kinds of patterns, but this one is kind of tricky, in the sense that it is not REALLY clear what is the benefit and, if misused, can bring more troubles than benefits.

So I found this post, from the Coding Delight Blog, which, at least for me, help to understand the idea behind the pattern.

“Favor composition over inheritance” is a phrase that I hear spoken a lot but which describes a concept I rarely actually see in real world code.  Every developer seems to know about it but few developers seem to actually put it into practice. This post will be looking at inheritance and some of the pitfalls of trying to create your domain model primarily through inheritance.

I can only assume that the reason why inheritance is so overused in real world code is due to the way that it is taught.  Back, far too many years ago, while I was still studying at university, the concepts of inheritance and polymorphism where both taught side by side, very early in the object-oriented programming course.  It seems as though these lessons were particularly memorable, because so much real-world code has giant inheritance chains.  We have ObscuredItems inheriting from DataItems inheriting from BasicItems which inherit from Items which inherit from BaseObjects.  Often times you will have to go five or six classes deep to find the root cause of a bug.

Favoring composition over inheritance helps us flatten those structures.  To illustrate this, I am going to take a look at a very simple problem.

I want to model real-world cars.  Specifically, I initially want to model the changes that a driver is applying to each car.  The customer in this case only wants me to model a Toyota Corolla.  The class should also have a string for the manufacturer name.  In this case I will deliberately favor inheritance.

Firstly, I’ll set up an abstract BaseCar class where I will define what I need: 4 wheels, a method for acceleration, a method for turning left and a method for turning right.

Next up, I will implement the functionality in my concrete car class.

Finally, I will then implement a concrete ToyotaCorolla class.

All fairly straight forward.  We have a nice little inheritance chain that seems to make sense (although perhaps I could have done away with the BaseCar class).

I submit this code to the customer and they are very happy.  They’re so happy that they will pay me more money to add extra features.  They now want me to implement a ToyotaCorollaSports class, which contains a rear-wheel drive version of the car.  In all other aspects it’s the same car, it’s only that the rear wheels are now powering the car.

Simple enough, I can inherit from the ToyotaCorolla and override the accelerate method.  I make the change and submit it to the customer.  They like what they see.

Two weeks later the customer has come back.  They love what we’ve done and want us to implement HondaCivic and HondaCivicSports classes.  Now we run into our first real problem.  The rear-wheel drive code is actually in the concrete ToyotaCorollaSports class.  What we need to do now is actually refactor our Car class into FrontWheelDriveCar and RearWheelDriveCar.  HondaCivic and ToyotaCorolla can then both inherit from the FrontWheelDriveCar class and the sports editions can both inherit from the RearWheelDriveCar class.

Our customers are very happy with what we have done so far and decide to commission us to create a four-wheel drive Mitsubishi Titan.

So we now have to create an AllWheelDriveCar and inherit from that for our Mitsubishi Titan.

class diagram
Finally, the customer comes along and asks us to model for them a new experimental four-wheel drive buggy that is designed to go on sand and turns with all four wheels.  A two-wheel drive buggy is also available (it also turns with all four wheels).

Now we have a problem.  We will obviously be deriving from our four-wheel drive class for the four-wheel drive model and the two-wheel drive class for the two-wheel drive model, but we will also have to override our TurnLeft and TurnRight methods in both classes, and the code will be duplicated.

Arggg!  Duplicated code is the enemy of maintainability. The best solution to this problem is to switch our thinking. Instead of inheriting all of our functionality, we should compose our classes from pieces of related functionality.

Next up: a better way to solve the same problem.

Lessons Learned in Software Development | Henrik Warne’s blog

Henrik Warne’s Lessons Learned in Software Development

I wanted to share this post from 2015 from Henrik Warne’s Blog for a while, as I agree with most of it and have been trying to follow it from the first reading.

If you are a software engineer, or is involved with software development in any level, this post will certainly be worth of your time.

Azure Web Jobs – Creating your first Azure Web Job from Scratch

So, you have just created your first Web App in Azure, and it is working like a charm. You have all the scalability you need and you know exactly how to store your data in the many options that Azure provide. What else do you need? Well, what will you do if you need to run some asynchronous background processing, like processing images or batch data? That is when Azure Web Jobs comes in handy.

What are Azure Web Jobs?

Straight from Azure documentation web site:

WebJobs is a feature of Azure App Service that enables you to run a program or script in the same context as a web app, API app, or mobile app. The purpose of the WebJobs SDK is to simplify the code you write for common tasks that a WebJob can perform, such as image processing, queue processing, RSS aggregation, file maintenance, and sending emails.

So, as you can see, it can perfectly fit the role of asynchronous background processing and with one interesting advantage, Web Jobs have very powerful integration with other Azure Services like the Service Bus and the Storage Services, making it incredibly easy not only to read/write data to this services but also to use them as TRIGGERS, avoiding the use of scheduled processing.

Let’s begin.

Creating your first ‘Azure Web Job’ from Scratch

The idea here is to create a simple Web Job that will be triggered after an item is added to an Azure Queue, and after very little parsing, save it to the Azure Tables Service.

The Setup

The first thing we are going to need is an Azure Account. If you don’t already have one, you can create one here, for free. Then we will install the Azure CLI 2.0, the installation instructions for all platforms can be found here. You may also want to install the Azure Storage Explorer, a tool that we will use to manage our Storage Account for testing.

Now we need to setup the resources in Azure to which the Web Job will connect. I’ll give you a list of commands from the Azure CLI that must be execute in a shell prompt.

First things first, we need to login to Azure through the console.

Then we need to create the Resource Group that will group all our resources.

Storage Account

Next step, create the storage account.

Then we create the Queue, that will be the source for our data, and the Table, which will be the destination of the processed data.

That’s all we need in the Storage service. Now we need to create the App that will host our Web Jobs.

App Service

And last, but not least, let’s configure our Connection Strings for the App:

And that is it for the Setup. Now, we can begin the coding.

Finally! Web Jobs

The Coding

For the coding part we can use whatever code editor we prefer. I will use Visual Studio Code, as it offers great support for coding C#.

As for the programming language, you may be surprised to know that Azure supports a lot of programming/scripting languages in the Web Jobs SDK, so you can choose the one you like the most. For this exercise, I will use C# because I feel like doing so 🙂

Start the Project

As I want this article to be as multi platform as possible, I will create a new project using the dotnet CLI. Open a shell prompt, navigate to the directory of your Web Job and type the following command:

Unfortunately the Web Jobs SDK has no support yet for the .NET Core Framework, so we have to make a small modification to the .csproj file, so we can use .NET Framework v4.5x.

The final file should look like this:

It is important to understand that a .NET Core Application can be executed by a Web Job, it only cannot make use of the Web Jobs SDK, which makes it much easier to integrate with other Azure Services

Azure Web Jobs SDK

Back to the shell prompt, we need to do three things. Add the Web Jobs SDK Package, restore the packages and build the project.

Code Host

It is worth mentioning now that one Web Job project has, at least, two main components:

  • The Code Host
    • This is the Entrypoint for the application, and this is where we should do all the configuration for our Web Job
  • A Trigger
    • Our project must have at least one Trigger, but it can have many others. In this case we will use only one trigger, fired by a new entry in our Queue.

Let’s start with the Code Host, which will be placed in the Main method of our code and will be the starting point of the application

That’s it 😀

Seriously Web Jobs?

No! I am not. The Host is, as the name implies, a piece of code that will configure your web job and control the lifetime of the code. It can be a lot bigger than this, including all sorts of configurations, but that is all we need for a simple Web Job.

The Trigger

The trigger is where the real business logic of our Web Job live or, at least, where it begin. In our case we will have a single method that takes a QueueTrigger and records the data to a Table. The table will also be represented through a parameter, to which we will save the data.

This is the method code:

Simple enough, isn’t it?

The method gets three parameters, the first one is the trigger itself, the message in the queue, notice that the attribute of the parameter specifies which queue the message comes from. The second parameter has the “out” keyword, specifying that is the output of the code and the parameter attribute also specifies the Table to which the data must go. The last parameter is a TextWriter object that the Azure SDK injects so you can log information to the Azure Log Console.

The model for the Queue is a simple POCO class, nothing special about it. The model for the Table inherits from “TableEntity” making it suitable to be saved to an Azure Table.

We are almost there! Only one step missing!

Deploy Web Jobs!

The Deploy

Now we have to deploy our Web Job to Azure, which is actually pretty simple. First thing we want to do is to build the project, to make sure that everything is in place, back to the shell prompt!

We should get a result like this:

Deploy Web Jobs

Navigate to the directory showed in the build command, in my case C:\Code\AzureCoderWebJob\bin\Debug\net45\, then we will zip the content of the folder.

Zipped Web Job

Now you have to open the Azure Portal, and login with your account.

In the Dashboard page, look for the App Service you created during the setup and open it. In the App Service Blade, under “Settings”, look for the option “WebJobs” and click on it, the WebJobs Blade will be opened, and at the top you should see a button “Add”, click on it. The Blade to add a new WebJob will be opened, and we will have to fill some information:

Add Web Job

The name is simply an identifier for the WebJob, the File must be the Zip file we have just created.

The possible “Type”s are “Continuous” and “Triggered”, it may cause a little confusion but we want to keep the Continuous Type.

The scale is what define if the WebJob will run in only one instance of the App Service or in all the instances, scaling with the Web App, it is not so relevant for our WebJob, so we will keep the default “Multi-instance”.

After filling all the fields, click in “OK”, wait for the deployment and process and… that’s it 🙂 You have just deployed your first WebJob created from scratch! But, how can we test it?

The Test

Let’s start by opening the “Logs” for our deployed WebJob. After we deployed the WebJob, we will be sent back to the WebJobs list Blade. In this list, select the WebJob and click in “Logs”. The Logs will be opened in another Tab of the Web Browser. We should see something like this:

Web Jobs Logs

Click on the title of the Web Job and you should see a small console, with the execution details for the Web Job:

Web Jobs Log

As you can see, our “ProcessQueue” method has been detected!

Now we must add a new item to the azure-coder-queue, using the Azure Storage Explorer…

…and then look at the log again:

Log Web Jobs

Our message has been successfully processed! Now, if we take a look at the contents of the AzureCoderTable, also using Azure Storage Explorer, we should see our item added to the table:

Web Jobs Table

Happy Web Job

And, finally, that is all you need to know to create a very simple WebJob from scratch! Most of what I showned here should work fine in Linux and Mac OS (apart from the usage of .NET Framework) but, unfortunatly, I am not able to test every step in these platforms, so let me know if you try and have any problem!

I am really sorry for the long post 🙂

Long Web Job Post