Extending Sitecore.Services.Client results

Last year, David Peterson posted an article about Extending the Sitecore Services Client. Though that is the most elegant solution, Sitecore (-Services Client) doesn’t come with dependency injection out of the box. I tried to go the other way around, and modified the results by adding actionfilters. I’d rather see Sitecore modifying their code to easily override the modelfactory used by the default HandlerProvider somehow, but this solution will work for now.

First, we will create a config include file that adds a step to the initialize pipeline:

Now, let’s create this very simple class:

So, all this does is register a new ActionFilter to the list of global WebAPI filters.

Now, for the real work, we add the actionfilter class:

So, when any WebApi controller action is executed, this class’ OnActionExecutedAsync method will get invoked. This method will check if the controller action has returned an instance of ItemModel or an IEnumerable of ItemModel.
If so, it calls EnrichItemModel. As you can see, EnrichItemModel extends the returned ItemModels with extra fields. In this case an array of all TemplateIds, an array of all ParentIds and a full url to the item. If the user is in Experience Editor mode, all field-editors are returned as HTML as well.

That is all there is to it! The code is part of a project hosted at GitHub. A project that is a nice R&D project I will blog about in the near future.