Using ASP.NET Web API in Kentico 8.1

   —   
This guide will show you how to create HTTP services using Web API in Kentico 8.1. Since Kentico itself uses Web API for its web services, creating custom Web API services requires some manual actions not required when creating Web API services in clean web project.

Why would you want to use Web API?

Web API is a Microsoft technology that’s great for creating lightweight HTTP APIs. Web API allows you to:
  • easily call the HTTP service using AJAX from any JavaScript framework
  • get rid of all the useless code in the application life cycle - you can build truly stateless services (by default, not even HTTP sessions are used)
  • completely decouple the front end from the back end
  • open the possibility of consuming  the API from multiple sources, like other servers or mobile applications

Web API background

Web API is part of the ASP.NET web stack developed by Microsoft. Web API currently exists in two major versions.

Web API 1

The full name of the first version of Web API is Microsoft ASP.NET Web API (RC) 4.XXX and can be obtained from NuGet. The confusing version number (1 vs. 4) is due to the fact that Web API 1 was released together with ASP.NET MVC 4, so the version numbers were kept in sync.

Web API 1 is the version of Web API that we use in Kentico for our own internal APIs. Those APIs are exposed at the /cmsapi/ endpoint and are not meant to be used by customers. We use version 1 of Web API, because the newer versions do not support .NET 4, which is supported by Kentico.

Web API 2 

At the time of writing of this article, the latest version of Web API can be obtained from NuGet here. This version is officially called Microsoft ASP.NET Web API 2.2 5.2.2. Web API 2 versions aren’t tied to MVC anymore. We did not use this version in Kentico, because it is only supported on .NET 4.5.

Since March 2012, Web API is open-source and its source code along with the source code of MVC and Web Pages can be obtained here.

How to use Web API 1 with Kentico?

If Web API 1 is enough for you, all you have to do in addition to the typical setup of Web API is to register API controllers with our RegisterApiController attribute, as shown in the sample code later in this article.

We require API controllers to be registered in order to speed up the process of controller lookup, which happens during the application startup.

The following list shows all steps you need to do in order to create a Web API service in a separate project in your Kentico solution:

  1. In the custom project, add references to the CMS.Base, CMS.Core, CMS.DataEngine and CMS.WebApi assemblies located in the Lib folder.
  2. Add the [assembly: CMS.AssemblyDiscoverable] attribute to the project’s AssemblyInfo.cs file.
  3. Add references to the Newtonsoft.Json, System.Net.Http, System.Net.Http.Formatting, System.Web.Http and System.Web.Http.WebHost assemblies located in the CMS/CMSDependencies folder and set the Copy Local property of the references to false.
  4. Register all your controllers using the [assembly: RegisterApiController(typeof(MyWebAPIController))] attribute as shown in the code sample below.
  5. Implement a Kentico module and add your custom startup logic (like route registration) to the module’s initialization (see Initializing modules to run custom code in the documentation, or classes in the Module folder of our sample project).
  6. Rebuild the solution.
Code sample: Defining Web API controllers
using System; using System.Net; using System.Net.Http; using System.Web.Http; using CMS.WebAPI; [assembly: RegisterApiController(typeof(MyWebAPIController))] namespace MyCompany.MySpace { public class MyWebAPIController : ApiController { public string Get(int id) { // You can return a variety of things here, for more details see http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results return "Hello world " + id; } } }

Code sample: Register custom routes that do not conflict with "cmsapi" or any page paths. Insert this code to your module’s OnInit() method as shown in our sample project.
GlobalConfiguration.Configuration.Routes.MapHttpRoute("customapi", "customapi/{controller}/{id}", new { id = RouteParameter.Optional });

Code sample: Consuming API using jQuery:
$http.get("http://myserver/customapi/MyWebAPI", { id: 1}) .success(function (data) { alert(data); }) .error(function(error) { // handle the error });

You can download the sample Kentico 8.1 project with Web API 1 service.

How to use Web API 2 with Kentico?

If you prefer to use Web API 2, the solution is little bit more complicated. Please follow the steps in the list below in order to create Web API 2 services.
 
  1. Add a new class library project containing your ApiControllers to the Kentico solution and reference it in the CMSApp project (or reference it in your web site if you don't use a web application type project).
  2. In your project, add references to the CMS.Base, CMS.Core and CMS.DataEngine assemblies located in Lib folder.
  3. Add the [assembly: CMS.AssemblyDiscoverable] attribute to the AssemblyInfo.cs file.
  4. Implement a Kentico module and add your custom startup logic (like route registration or initialization of AttributeRoutes) to the module’s initialization (see Initializing modules to run custom code).
  5. Delete all dlls from the Lib/MVC folder.
  6. Remove the CMSApp_MVC project from the solution or update it to MVC 5 if you use it for MVC (please see Upgrading the MVC version in the documentation).
  7. Create the Newtonsoft.Json.6.0.0.0 folder in CMS/CMSDependencies and place the Newtonsoft.Json.dll in version 6.0.0.0 here. This step assumes the version of Web API you use requires Newtonsoft.Json version 6.0.0.0. You need to update the folder name in CMSDependencies and the dll to always contain the version that your Web API requires. This basically means that you need to synchronize Newtonsoft.Json from /packages to CMS/CMSDependencies every time you update Web API. CMSDependencies is a special folder that allows us to use libraries even though they are not in bin and is the only way to use two different versions of the same assembly at the same time.
  8. Rebuild the solution.
Optionally, you can add our sample class library project to your solution and place your ApiControllers in there.

Conclusion

So which Web API version should you use? If you are running on .NET 4.0, you are restricted to Web API 1, because Web API 2 does not support .NET 4.0. However, if your project runs on .NET 4.5, we recommend using Web API 2, as it is more future-proof.

We are continuously reducing our dependencies on third party libraries. In general, we try not to force our customers to use specific versions of third party libraries and that’s also the case with Web API. We are definitely aware that the current solution is not ideal and we are working on improving it in the next minor versions of Kentico, so that you will be able to use Web API just like you would outside of Kentico.

All that being said, we need to warn you that because of the improvements we plan to make in regard to third party libraries (and Web API in particular), you may need to perform additional manual changes when upgrading to Kentico 8.2 if you decide to use Web API with Kentico 8.1. A step-by-step guide will be provided in the Upgrade instructions.
Share this article on   LinkedIn

Comments

Steve commented on

We experienced the same dashboard issue in Kentico 8.2.5. Is there a known solution?

Jakub commented on

Hi William,

dashboard should work just fine after upgrading to Web API 2. Would it be possible for you to send me the detailed description of the error you are getting (event log or JavaScript console) to jakubk@kentico.com? A zipped project folder would help as well. Thanks.

Jakub

William commented on

It appears that after upgrading to web api 2 in v8 the dashboard no longer works. Is there a fix for this?