Last active
August 29, 2015 14:26
-
-
Save agehrke/a3b3da83bfd9d7b109f9 to your computer and use it in GitHub Desktop.
Web API controller in Sitecore 8 - including async/await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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 | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Id":"1", | |
"DatabaseName":"master", | |
"DatebaseNameAfterAwait":"master", | |
"User":"sitecore\\admin", | |
"UserAfterAwait":"sitecore\\admin", | |
"Language":"da-DK", | |
"LanguageAfterAwait":"da-DK" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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