Using the Sitecore Database in Web API

Web API has no access to the current Sitecore Context your page is in. With that said, there’s no stopping you from creating an instance of the database on the fly as long as you know which database your site is using. 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 provided by 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);
    }
}

Now, I do not recommend that you have your Sitecore logic inside your controller, rather have a helper class contain your Sitecore logic, and use it in the controller.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s