I recently started an ASP.NET MVC 5 project, and having used Reactive Extensions (Rx) for five years in other projects I was really keen on using Rx in my ASP.NET code also. The question was how? Well, after some tinkering I figured it all out.

Asynchronous action methods

The first thing we’ll take advantage of is the fact that action methods in controllers can be asynchronous. Instead of declaring your action method like this:

You type:

That alone frees up the web server by asynchronously waiting for the response to ‘come back’. This means it can serve other requests in the meantime. The next step is of course converting an observable Rx chain like this:

into an ActionResult . Well, to do that we need an extension method. Basically, we want to convert an IObservable<T> to a  Task<T> . The reason is of course to match the action method’s return type.

Error handling

Also, we need to incorporate error handling, so that any exceptions are handled and the appropriate return value is used. In general I always prefer to have generic (“catch-all”) error handling in place, and then, if needed, we can customize it for specific cases. That way no errors slip through.

How to use it

I decided to use optional parameters for the error handling. Here’s what the default use of my extension method looks like:

You could also write:

And if you want to do specific error handling, you could do:

The extension method

As you can see from the code above you can specify an optional scheduler, as well as a custom timeout period.

Source code

The full source code is available on Github.


Posted by Henrik

Writes large scale software for a living.

Leave a Reply