Creating a web API in Sitecore for ajax calls with in Sitecore context

5/21/2018 sitecore-custom-routes sitecore-api sitecore-best-practises

Web Api's in Sitecore instance with Sitecore context.

Sometimes we do need to create web APIs for ajax calls in our Sitecore solution.

By doing a normal web API will not initialize Sitecore pipeline, so this makes Sitecore.Context.Site || Sitecore.Context.Database null. 

To get the normal Sitecore context we need to add a custom route to route table and add it to Sitecore pipeline.

Steps to follow:

1. Add your custom Route to RouteTable.
2. Add your custom processor at the end of the initialize pipeline.
3. Inherit your custom Sitecore API controller from SitecoreController

Adding custom Route to RouteTable

    public class RegisterCustomRoute
        public virtual void Process(PipelineArgs args)
            RouteTable.Routes.MapRoute("RouteName", "CustomApi/{controller}/{action}/");



Add your custom processor at the end of the initialize pipeline

        <processor patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" type="sitecoreBlog.tools4geeks.Custom.RegisterCustomRoute, sitecoreBlog.tools4geeks"/>


While creating a controller inherit it from SitecoreController.

This is it, now you got fully flexible sitecore API which can be useful for ajax calls with in sitecoreContext.