Andreas Gehrke

Web API controller with async/await in Sitecore 8

So you want to create Web API controllers in a Sitecore 8 solution? Use Sitecore.Services.Infrastructure.Web.Http.ServicesApiController and add Sitecore.Services.Core.ServicesControllerAttribute to namespace your controller. Read Developer's Guide to Sitecore.Services.Client (PDF) from page 61 and onward. Controllers will be reachable at:

/sitecore/api/ssc/{namespace}/{controller}/{id}/{action}

That's it. No routing setup, no pipeline fiddling. Quick and easy! Just note that Sitecore does not support dependency injection in the controller - at least out of the box.

Below is a full example that shows async/await in a Web API controller - note the aspnet:UseTaskFriendlySynchronizationContext appSetting in Web.config.

You might also want to check my post on disabling of Sitecore Web API filters.

ApiController.cs:

/// <summary>
/// Note that name of controller does not matter when using ServicesControllerAttribute like below.
/// You can reach the Test() action on url: /sitecore/api/ssc/example1/andreas/1/test
/// </summary>
[Sitecore.Services.Core.ServicesController("example1.andreas")]
public class ApiController : Sitecore.Services.Infrastructure.Web.Http.ServicesApiController
{
	[HttpGet]
	public async Task<IHttpActionResult> Test(string id)
	{
		var database = Sitecore.Context.Database;
		var user = Sitecore.Context.User;
		var language = Sitecore.Context.Language;

		// Emulate async work
		await Task.Delay(500);

		var databaseAfterAwait = Sitecore.Context.Database;
		var userAfterAwait = Sitecore.Context.User;
		var languageAfterAwait = Sitecore.Context.Language;

		return Ok(new
		{
			Id = id,
			DatabaseName = database.Name,
			DatebaseNameAfterAwait = databaseAfterAwait?.Name,
			User = user?.Name,
			UserAfterAwait = userAfterAwait?.Name,
			Language = language.Name,
			LanguageAfterAwait = languageAfterAwait?.Name
		});
	}
}

Output.json:

{  
  "Id":"1",
  "DatabaseName":"master",
  "DatebaseNameAfterAwait":"master",
  "User":"sitecore\\admin",
  "UserAfterAwait":"sitecore\\admin",
  "Language":"da-DK",
  "LanguageAfterAwait":"da-DK"
}

Web.config:

<appSettings>
  <!-- Add the following setting for proper flowing HttpContext across awaits -->
  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>

Tags: #dotnet-dev