Query Sitecore Items in Web API

item query Sitecore web api

Building client-side web apps is the new trend, which means a lot of XHR requests to the back-end. Luckily, Sitecore provides a highly configurable Item Web API to help you with querying items from the client-side. But if you want results that are bound to your models and end-points not containing your query, then you will resort to querying items against the context database using ASP.Net Web API… only that… it doesn’t work out of the box.

Web API has no access to the current Sitecore Context your page is in. With that said, there’s no stopping you from querying Sitecore items as long as you know which database name your site is using and from that you can create an instance of the database object. You can either create a config value so you know which database name to use or you can fetch it programmatically. I will show you how you can do the latter.

First, we will need to create a function to retrieve the current Sitecore Site.

public static Sitecore.Web.SiteInfo GetSitecoreSite()
{
    var url = System.Web.HttpContext.Current.Request.Url;
    var query = Sitecore.Configuration.Settings.Sites.Where(n => n.HostName.Contains(url.Host));

    if (query.Count() == 1) return query.First();

    return
        query.FirstOrDefault(n => url.AbsolutePath.Contains(n.PhysicalFolder)) ??
        query.FirstOrDefault(n => n.PhysicalFolder == "/");
}

Assuming you have your Sitecore logic in your controller you can then proceed to create the database object using the database name from the site object.

public class ItemController : ApiController
{
    private readonly Sitecore.Data.Database Db = Sitecore.Data.Database.GetDatabase(GetSitecoreSite().Database);

    public HttpResponseMessage Get(string id)
    {
        var item = Db.GetItem(id);
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }
}

Make sure in the end you do not have your querying code written directly in the controller, rather in a helper class to keep it clean.

No Thoughts to Query Sitecore Items in Web API

Comments are closed.