You do not need to write this code every time …
Nowadays, almost every Sitecore solution needs a custom Web API endpoint implementation. One of the common web API uses cases when a front-end component needs to be dynamically rendered at the client-side (eg a browser page). However, there could be some challenging factors of the back-end implementation:
- The Web API response data needs to be presented in JSON format.
- The Web API response data is calculated based on multiple Sitecore items.
– The data evaluation is expensive in the performance perspective so it has to be cached.
– The data cache needs to be invalidated when the corresponding Sitecore items are changed.
- The data to be transferred over the network only the data has been changed, otherwise, the client-side cached version of it will be used.
To serve the data in JSON format via Web API endpoint, it is possible to use ASP.NET Web API 2. Therefore, no significant challenges here.
To cache the data Sitecore HTML Cache can be used. Sitecore HTML Cache invalidates automatically by Sitecore (normally, on Publish). In this case, the Controller Action would need to produce the data and let Sitecore HTML Cache store it. However, it would be good to remove the cache storage responsibility from the Controller Action. In addition, it would be necessary to avoid Controller Action execution if the data already exists in the cache. Luckily, ASP.NET Web API 2 Action Filter attributes exist that can help to do this. The Action Filter attribute has two handlers:
- OnActionExecuting – allows accessing the current request context, including the request parameter object (s) and terminate the request with a custom response without going ahead with the Controller Action execution.
- OnActionExecuted – allows accessing the response result in the cache.
To address the redundant data transfer between the server and the client, HTTP ETag mechanism can be used which allows producing 304 Not Modified HTTP response. Again, A SP.NET Web API 2 can help to solve this.
HTTP ETag mechanism, including Sitecore HTML Cache, can be applied in a generic way to any controller using Action Filter attributes.