7

Does anybody have any experience with Web API and Sitecore? I've got a custom database for data not managed by Sitecore, but will be presented alongside Sitecore data.

The API calls work fine when called directly, but after publishing with the Sitecore site, the site won't load and gives an error saying:

"The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code."

I've tried adding EnsureInitialized() to the startup code, like it says, but it gives the same error.

My API is not calling any Sitecore data.

I added a RegisterRoutes class to Sitecore.Pipelines and patched Sitecore with RegisterRoutes.config after Sitecore.Pipelines.Loader.EnsureAnonymousUsers

My relevant files are as follows:

WebApiConfig.cs

using System;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace Feature.DataAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // This block of code sets the application to emit json globally by default
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
                new RequestHeaderMapping("Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true,
                    "application/json"));
        }
    }
}

Global.asax.cs

using System.Web.Http;

namespace Feature.DataAPI
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            // This block of code is to handle a circular reference error when serializing the json output
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
                Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            GlobalConfiguration.Configuration.EnsureInitialized();
        }
    }
}

RegisterRoutes.cs

using Sitecore.Pipelines;
using System.Web.Http;
using System.Web.Http.Routing;

namespace Feature.DataAPI.Pipelines
{    
    public class RegisterRoutes
    {
        public void Process(PipelineArgs args)
        {
            GlobalConfiguration.Configure(Configure);
        }

        private static void Configure(HttpConfiguration configuration)
        {   
            configuration.Routes.Add("API", new HttpRoute("sitecore/api/{controller}/{id}"));
        }
    }
}

RegisterRoutes.config

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="Feature.DataAPI.Pipelines.RegisterRoutes,Feature.DataAPI" patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

Update:

After following @Andrey's advice, I have made some progress and am now getting this error:

The controller for path '/dataapi/Product/1' was not found or does not implement IController.

So at least Sitecore is finding it now. I read in this blog here that Sitecore is throwing an error because it is expecting IController whereas Web API implements ApiController instead. It suggests modifying the order of registrations in the Application_Start, but I can no longer modify this file in Sitecore 8.2 as stated by Soren. So, do I have to alter where the processor is patched in the RegisterRoutes.config file? If so, where should it be placed instead?

4
  • this means that there is a clash in the registrations. can you show the route that you use? Jan 12, 2017 at 13:58
  • @Andrey I updated the route, per your suggestion, to "dataapi/{controller}/{id}" and tried to access it with "website/dataapi/Product/1"
    – Iceape
    Jan 12, 2017 at 15:16
  • i think you miss the {action} in your route. Jan 12, 2017 at 15:39
  • I don't think the {action} is always necessary in a route configuration. At least, this is the default route generated by the Web API template in Visual Studio. I think it matches actions based on method signature and which HTTP verb is used. But in either case, I added it to my route and am still getting the same error.
    – Iceape
    Jan 12, 2017 at 15:53

2 Answers 2

5

I think you need to move the stuff in your WebApiApplication.Application_Start method to the initialize pipeline like you are doing with the RegisterRoutes class.

In Sitecore 8.2 (or somewhere around there) they made Application_Start internal so you can't override it anymore. I've been told this has been marked as a bug at Sitecore and I supposed it will be fixed in a later release, but it hasn't as of 8.2 Update-2.

1
  • You can still do this, but you shouldn't. As you stated, the initialize pipeline is what every best practice and recommendation out there says to use. Do not change files provided from Sitecore unless absolutely necessary. You can also see this thread for more details: sitecore.stackexchange.com/questions/6998/… Oct 26, 2017 at 15:29
2

Sitecore has its own Global.asax which type is Sitecore.Web.Application.

In your example, it looks like you override the default sitecore global.asax and this causes conflicts/issues.

In order to eliminate conflicts, you should start from deriving your application class from the Sitecore Application.

Also, please use this technique to register custom routes instead: https://kb.sitecore.net/articles/700677

13
  • Hi Andrey, thank you for your help. I followed the instructions in the guide, and restored the original Global.asax.cs as my custom one had overridden the Sitecore version in my webroot. But now when I call the API directly I get an error saying "HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid." and "Cannot read configuration file". Any thoughts on what else I need to do?
    – Iceape
    Jan 12, 2017 at 10:43
  • Hi @Iceape check if you are not overriding the web.config as well Jan 12, 2017 at 12:33
  • I have its Build Action set to None and just confirmed that the web.config in the webroot is the normal Sitecore web.config. Do I need to add anything to this config file? Additionally, my Sitecore site is back to normal now, except now the DataAPI is no longer working, even when called directly. Also when go into IIS and click on Configuration Editor for my DataAPI it also says " Filename: \\?\C:\Projects\Website\src\Feature\DataAPI\Feature.DataAPI\web.config Error: Cannot read configuration file"
    – Iceape
    Jan 12, 2017 at 12:35
  • @Iceape Basically, the exception that you mention is indeed related to the web.config file. It is either 1) missing; 2) corrupt; 3) incorrect The trick is that you have to use this web.config if you are calling your API straight and not use it if you are calling you API from the sitecore website. As a side note, make sure that you migrate some important sections from the api web.config to the sitecore web.config (also by using includes where possible) Jan 12, 2017 at 12:39
  • @Iceape also check that C:\Projects\Website\src\Feature\DataAPI\Feature.DataAPI\‌​web.config file xml is correct Jan 12, 2017 at 12:41

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.