0

I'm working on a project where I have a controller with a few endpoints which can be called from Sitecore and non-Sitecore sites. This works fine. Now I have to add a different endpoint that needs to read an item from the context database in order to return the requested data. My problem is that when I try to access the specified item I get an exception due to the database being null.

I know that the controller is not in the Sitecore context but I don't know how to solve/work around it.

Below you will find a short snippet of the controller.

[RoutePrefix("api/test")]
[HandleException]
public class TestApiController : Controller
{
    public TestApiController()
    {
        // some stuff
    }

    [HttpPost]
    [Route("SpecialAction")]
    public async Task<string> SpecialAction(string data)
    {
        string itemID = "{443FA245-623A-4EEF-B519-281A9C709B7C}";
        Item specialItem = Sitecore.Context.Database.GetItem(new Sitecore.Data.ID(itemID));
        if (specialItem.HasChildren)
        {
            // logic
        }
        return response;
    }
}

1 Answer 1

3

Try to get database using Sitecore Configuration Factory and get the item from that database-

Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");
masterDB.GetItem(new Sitecore.Data.ID(itemID))
2
  • Although this threw a could not find configuration node databases/database @id='master' error it got me thinking. If I call the endpoint from a Sitecore page it works fine but not from within my test or other applications which have no connection to Sitecore. But this is OK for now. Thanks for your help!
    – Flo
    Commented Sep 2, 2020 at 6:10
  • are you testing this on CD? Then pass the database accordingly like web Commented Sep 2, 2020 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.