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:

public class ProductController : Controller
{
    public ActionResult Index(ProductListCommand command)
    {
        return command.Execute();
    }

    public ActionResult Create()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(ProductCreateCommand command)
    {
        return command.Execute();
    }

    public ActionResult Edit(ProductGetCommand command)
    {
        return command.Execute();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(ProductUpdateCommand command)
    {
        return command.Execute();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Delete(ProductDeleteCommand command)
    {
        return command.Execute();
    }
}

Now, let see what is happening inside the Commands, first the ProductCreateCommand:

public class ProductCreateCommand : RESTifyCommand
{
    private readonly IRepository<Product> repository;

    public ProductCreateCommand(IRepository<Product> repository)
    {
        this.repository = repository;
    }

    public Product Product
    {
        get;
        set;
    }

    protected override void ExecuteCore()
    {
        // You should use a powerful validation engine like DataAnnotation or xVal 
        // over here, I am using the dumb if/else for the shake of simplicity.

        if (string.IsNullOrEmpty(Product.Name))
        {
            ModelState.AddModelError("Product.Name", "Name cannot be blank.");
        }

        if (!Product.Price.HasValue)
        {
            ModelState.AddModelError("Product.Price", "Price cannot be blank.");
        }

        if (Product.Price.HasValue && (Product.Price <= 0))
        {
            ModelState.AddModelError("Product.Price", "Invalid price. Price cannot be zero or negative.");
        }

        if (ModelState.IsValid)
        {
            repository.Create(Product);
            ViewData.Model = Product;
        }
    }
}

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.

public class CommandBinder : DefaultModelBinder
{
    private readonly Func<Type, IRESTifyCommand> factory;
    private readonly IFormatDetector formatDetector;

    public CommandBinder(Func<Type, IRESTifyCommand> factory, IFormatDetector formatDetector)
    {
        Invariant.IsNotNull(factory, "factory");
        Invariant.IsNotNull(formatDetector, "formatDetector");

        this.factory = factory;
        this.formatDetector = formatDetector;
    }

    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        Invariant.IsNotNull(controllerContext, "controllerContext");
        Invariant.IsNotNull(modelType, "modelType");

        IRESTifyCommand command = factory(modelType);
        RESTifyFormats format = formatDetector.Detect(controllerContext.HttpContext.Request);

        command.SetRequestFormat(format);
        command.SetControllerContext(controllerContext);

        return command;
    }
}

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:

  1. 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.
  2. Serialization support other than DataContractSerializer, which means you can serialize anything including the anonymous objects.
  3. Support for Registering JavaScriptConverter to shape up the json output. (It is still missing in the ASP.NET MVC Framework).
  4. Support for Registering KnownTypes for the DataContractSerializer.
  5. Fully extensible, anything can be replaced without modifying the core.
  6. 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:

public virtual ActionResult Execute()
{
    if (!CanExecute)
    {
        return Unsupported();
    }

    ExecuteCore();

    return BuildResult();
}

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 ActionResult RESTifyUnsupportedResult 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.

protected virtual ActionResult BuildResult()
{
    if (RequestedFormat == RESTifyFormats.Html)
    {
        return new ViewResult { ViewData = ViewData, TempData = TempData };
    }

    IResultFormatter formatter = ResultFormatters[RequestedFormat];

    if (RequestedFormat == RESTifyFormats.Jsonp)
    {
        IJsonpResultFormatter jsonpFormatter = formatter as IJsonpResultFormatter;

        if (jsonpFormatter == null)
        {
            throw new InvalidOperationException(TextResource.InvalidResultFormatterTypeRegisteredForJsonp.FormatWith(formatter.GetType().FullName));
        }

        jsonpFormatter.JsonpCallbackFunction = JsonpFunctionNameDetector.Detect(HttpContext.Request);
    }

    return new RESTifyResult(RequestedFormat, formatter, HttpContext.Request.ContentEncoding, Model, ModelState);
}

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.

public override void ExecuteResult(ControllerContext context)
{
    Invariant.IsNotNull(context, "context");

    HttpResponseBase response = context.HttpContext.Response;

    response.Clear();

    response.ContentType = contentTypes[Format];

    if (ContentEncoding != null)
    {
        response.ContentEncoding = ContentEncoding;
    }

    string output = Formatter.Format(ContentEncoding, Model, ModelState);

    response.Write(output);
}

One last thing that you have to do, is adding some bootstrapping code in the global.asax or more preferably in your Bootstrapper.

public void ConfigureRESTify()
{
    RESTifySettings.Current
                   .SetCommandFactory(type => ServiceLocator.Current.GetInstance(type) as IRESTifyCommand)
                   .RegisterCommands();
}

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);

    ConfigureServiceLocator();
    ConfigureRESTify();
}

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:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(ProductCreateCommand command)
{
    return command.ExecuteAndRedirectToAction("Index").WhenFormatIsHtml();
}

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

Q: Looks like the Command object itself inherited from Controller.

A: No, it is not. This is the declaration:

public abstract class RESTifyCommand : IRESTifyCommand, IHideObjectMembers

Q: How do I on/off supported format?

A: To on/off supported formats globally use the RESTifySettings like the following:

RESTifySettings.Current
               .SetCommandDefaultFormats(RESTifyFormats.Html | RESTifyFormats.Json);

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:

public class ProductListCommand : RESTifyCommand
{
    protected override RESTifyFormats SupportedFormats
    {
        get
        {
            return RESTifyFormats.Html | RESTifyFormats.Atom;
        }
    }
}

Q: How do I register custom Result Formatter?

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.

Q: How can I play with it, where is the source code located?

A: You can check the live version over here or if you want to get the source, checkout my first open source project in GitHub.

That’s it for the day.
Shout it

6 Comments

  • Hi Kazi,

    You said, "I am using the dumb if/else for the shake of simplicity."

    May I know the smart way?

  • Yes I have mentioned the names of validation engines just before the line you quoted.

  • Very nice, and congratz for opening a Github account ;)
    Erik

  • Another layer of complexity. :)

    On the other hand - might be really handy if controllers grows rapidly.

  • 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:

    public ActionResult ActionName( ICommandInterface command )
    {
    if( !command.IsValid )
    {
    return View();
    }
    var result = command.Execute();
    return RedirectTo( /* build url / route using data in result */ );
    }

    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.

  • @Neal, if that's not too much asked - could you blog post about your approach? I like this idea but i just want to tidy up my controllers and not to RESTify them (yet).

Comments have been disabled for this content.