Skip to content

Instantly share code, notes, and snippets.

@agehrke
Last active August 29, 2015 14:26
Show Gist options
  • Save agehrke/a3b3da83bfd9d7b109f9 to your computer and use it in GitHub Desktop.
Save agehrke/a3b3da83bfd9d7b109f9 to your computer and use it in GitHub Desktop.
Web API controller in Sitecore 8 - including async/await
/// <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
});
}
}
{
"Id":"1",
"DatabaseName":"master",
"DatebaseNameAfterAwait":"master",
"User":"sitecore\\admin",
"UserAfterAwait":"sitecore\\admin",
"Language":"da-DK",
"LanguageAfterAwait":"da-DK"
}
<appSettings>
<!-- Add the following setting for proper flowing HttpContext across awaits -->
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment