Search code examples
c#asp.netapiasp.net-web-apikentico

How can I access Kentico content from Web API?


Using Kentico's documentation I've set up a new project in my Kentico solution with the following:

  • Microsoft.AspNet.WebApi from Nuget
  • Added [assembly: CMS.AssemblyDiscoverable] to AssemblyInfo.cs
  • Referenced:
    • CMS.Base
    • CMS.Core
    • CMS.DataEngine
  • Added a class which inherits CMS.DataEngine.Module and has the following in its OnInit():

    GlobalConfiguration.Configuration.Routes.MapHttpRoute( "customapi", "customapi/{controller}/{id}", new { id = RouteParameter.Optional });

  • Added a controller inheriting ApiController called TestController as per documentation referenced above.

Because I want this API hosted under the same domain as my main Kentico website I've then made this custom project a dependency of the CMCApp_AppCode project. When I re-build and run I can now call my API as expected at: http://dev.local/customapi/test

The problem is that now I want to work with Kentico's document API and return page data via the API. However, if I add calls to Kentico's API inside my API controller I get all sorts of errors. For example:

  1. Calling CMS.SiteProvider.SiteContext.CurrentSite returns:

Evaluation of method CMS.SiteProvider.SiteContext.get_CurrentSite requires calling method System.RuntimeType.IsDelegate, which cannot be called in this context.

  1. Calling CMS.DocumentEngine.DocumentHelper.GetDocument throws:

Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized.

Things I've tried:

  1. Adding the following at the start of the controller action but this makes no difference - CMS.DataEngine.CMSApplication.Init();
  2. Adding /customapi to the excluded URLs in Kentico settings.

So I'm completely stuck - how can I get Kentico to work with my web API?


Solution

  • This kind of exceptions only occur when debugging (while evaluating expressions in the watch or immediate window).

    Check that you have selected "Debug" (=not "Release") configuration when debugging. Configuration should be set to Debug

    Also, make sure that the debug configuration doesn't have "Optimize code" enabled. And that debug info is set to "Full" under "Advanced". Optimize code should be OFF

    If it doesn't help then just store results of your calls to variables and evaluate those. Other option would be logging the results using Debug or Trace as shown here: https://support.microsoft.com/en-us/help/815788/how-to-trace-and-debug-in-visual-c