RESTify – Extending ASP.NET MVC

Recently there has been a talk of Actionless Controller in ASP.NET MVC space. Basically we are doing a lot of things in the controller and that is the reason we often finds our controllers with number of dependencies in the constructor. Jeffrey Palermo initially suggested a version where he separated each action as a standalone controller which is good to reduce the number of dependency but it does not sound right to me. At the bottom of that post Neal Blomfield hinted about the Command Pattern which makes absolute sense. Since the release of our initial version, I have got some time to breathe, so I decided to give it a try. Initially the idea was, each Controller action method will accept a command object as parameter and the Controller will call the Execute method. The Command object will be responsible to perform the action which the Controller action methods usually do. Let me show you a sample controller which has nothing but some CRUD methods with Command objects:

First, it is inherited from a special base class RESTifyCommand, next we are injecting our dependency in the constructor as we do for the Controllers and at last, we are overriding the ExecuteCore method to perform our actual operation. Also check that we not writing any code to populate the Product, instead we are relying on the ASP.NET MVC Framework to populate it for us. The little difference between the ExecuteCore with a regular Controller action method is instead of returning any ActionResult(the method is a void()) we are only setting up the Model and ModelState. I will get back to the Execute() method after a little while, for the moment lets see how this Command object is created and passed backed to the Controller. One of the important thing when creating the Command Object is, we have to inject the dependencies in its constructor or more specifically we have to give the opportunity so that you can use your prefered IoC/DI framework to create these commands, also we need to utilize the rich ASP.NET MVC underlying features to automatically populate the other parts of the Command (for ex the Product property of the above example) and the thing that I really love of ASP.NET MVC framework is its extensibility. To create and populate the Command object we use a custom ModelBinder. Our ModelBinder is inherited from the DefaultModelBinder of ASP.NET MVC as we want to reuse the common behavior of the default binder, but instead of overriding the BindModel that you often see in most of the available ModelBinders, we are overriding the CreateModel method.

As you can see in the constructor we are accepting a Func to create the Command so that we do not have to refer to any external IoC/DI component, we are also accepting another object IFormatDetector. Initially, my plan was to introduce the Command object in ASP.NET MVC, but after seeing both Nate Kohari’s Siesta and MS ASP.NET MVC REST SDK, I thought why not add some REST love into this. So the idea was after the Command objects performs its actual operation which we have seen in the above, it should also decide in which format it will return the data, the associated controller should not have any clue about this, all it has to do is call the Excecute() method of command and the rest it taken care by the Command. In the above, the formatDetector detects the requested format from HttpRequest and sets the Command requested format, so that Command can later return the result depending upon that. Although it is in very early stages and I am still working on it, yet there are some advantages of using it comparing to the above:

Out of the box support for HTML/XML/JSON/JSONP. There is no generic representation of ATOM/RSS, you need to write special formatters(IResultFormatter) to support those.

Serialization support other than DataContractSerializer, which means you can serialize anything including the anonymous objects.

Support for Registering JavaScriptConverter to shape up the json output. (It is still missing in the ASP.NET MVC Framework).

Support for Registering KnownTypes for the DataContractSerializer.

Fully extensible, anything can be replaced without modifying the core.

200+ Unit Tests which include more than 99% code coverage.

You can view the complete live demo, over here. As you can see the same Controller method is responsible for returning different formats, no condition checking, no if/else nothing, just call the Execute() of the Command. In the demo, I am using plain javascript instead of any library like jQuery/ASP.NET AJAX to show you that it is completely independent of the client side, you can use your prefered javascript library with this extension when working with your browser application.

Now lets get back to the original discussion, so far we have set the Model and ModelState, but did not see how the result is delivered to the client, lets see what is happening in the RESTIfyCommand’s Execute method:

First, we are checking whether the Command can execute, there are severeal reasons a Command cannot execute, for example the request format is not supported by the Command, which usually happens when you want to restrict certain formats from delivering to the client or formatter for the requested type is not registered or your code as you can override the method, if the command cannot execute we are returning a special ActionResultRESTifyUnsupportedResult which is basically returning HttpStatusCode 415(Unsupported Media Type). If the command is allowed to execute then it is calling the ExecuteCore() which means the code that we have written in the above and finally it is returning the result. Now lets see the code of BuildResult method.

As you can see, for the Html, we are returning the regular ViewResult, next for JSONP we are checking whether the registered formatter is appropriate for JSONP, as JSONP needs the additional callback method name, the rest of the part is very simple, we are returning our custom RESTifyResult with the required data, the RESTifyResult uses the provided ResultFormatter to write in the Response.

We are setting the factory method which you have seen in the CommandBinder in the above in the SetCommandFactory, I usually prefer to abstract the underlying IoC/DI with the CommonServiceLocator, if you do not like it, you use your preferred DI directly over here. Next, we are registering all Commands with our CommandBinder by scanning the referenced assemblies, if you do not like to scan you can use the overloaded version which accepts specific types or single assembly.

Now let me answer some of the common questions:

Q: How do I redirect to a action after the command executes, for example, in a CRUD operation when an object is created I want to redirect back to Index for the Html and for the others formats I just want to return the data.

A: There are few overloaded methods in the Command which you can use to redirect to other actions for a special format after the command executes. For example, in the above ProductController’s Create you can use the following:

The WhenFormatIsHtml is an extension methods there are other versions of it. Don’t worry about the validation it will not redirect if the validation fails (ModelState.IsValid == false).

Q: What about the other facilities that we often gets in the regular Controllers like Try/UpdateModel, UrlHelper etc etc.

A: Most of the facilities that are available in Controller is also available in Command but it does not includes those which are contradictory (methods that returns ActionResult (w/o redirecting) are excluded).

Now all your command will only support html and json or you can override the SupportedFormats property if you want to set it for a specific command, for example, now the ProductListCommand will only support Html and ATOM:

A: To register a formatter that will be applied to all, use the RegisterResultFormatter method, there is also Command specific version which will set the formatter for only that Command.

Q: How does the Serialization works?

A: Well when it comes to serialization in .NET Framework, we have two sets of serializers the regular serializers like XmlSerializer/JavaScriptSerializer and the new DataContractSerializers, but none of it can serve our purpose. For example, DataContractSerializers can only work when the serialized object is decorated with its required attributes, which means you cannot serialize anonymous objects or the objects that are beyond your control also if your object is buildup with other objects it requires to know those other objects. There are also issues with regular serializers. So instead of supporting only a single set, we are supporting both. When serializing we are first first checking whether the object is a known type to us, if it is a known type we use the DataContractSerializers if not we are using the regular serializers. By known type, I mean an object is decorated with DataContractSerializers attributes and it is registered to this extension. To register known types, you can use the RegisterKnownTypes method of RESTifySettings, it has similar overloaded versions of RegisterCommands.

Nice work. My comment on Palermo's post was the result of a significant amount of research / thinking prior to designing the basic architecture for a new project. I ended up heading down a similar path to the route you have taken ( and have been meaning to post my experiences ).

It is eerie how similar your implementation looks to the one I have. Key difference for me are all action parameters are interfaces ( I bind the model out of a Windsor container ).

My commands use the slightly looser definition that is based on the concept that the results of a command should not be able to cause side-effects in the system and therefore I often return simple result classes that effectively double up as view-models.

Application of the command pattern in this was also allows me to define context specific validation and perform that validation at the boundary of the system. I have wrapped this into an interface that the commands implement and execute validation via an action filter. Most of my actions now look similar to:

I have also created a separate but very similar query interface that allows me to identify and manage command and query semantics differently at a later point if I choose to. While some might call YAGNI on that, the distinction is important as often a command will have no result and simply execute / redirect whereas a query will usually be executed and the result used as a view model for the view.

Hoping to start building a simple cms at some point using this pattern and putting it out there as a sample for building CQS style MVC applications.