Search code examples
c#asp.net-web-apiasync-awaithttpcontext

HttpContext.Current null in async after await calls


HttpContext.Current null in async after await calls.

Here is my code:

if (!string.IsNullOrEmpty(securityGroupName))
{
    // To remove the domain name from the security group name.
    string securityGroupDisplayName = securityGroupName.Split('\\')[1];
    string serviceSecurityGroupId = await this.graphApiClient.GetGroupIdAsync(securityGroupDisplayName).ConfigureAwait(false);

    if (!string.IsNullOrEmpty(serviceSecurityGroupId))
    {
        Task securityGroupRoleAddTask = this.CheckMembershipAndAddRole(serviceSecurityGroupId, userId, securityGroupName);
        Task flightAdminRoleAddTask = this.CheckMembershipAndAddRole(FlightAdminSecurityGroupId, userId, FlightAdminRoleName);
        Task.WaitAll(securityGroupRoleAddTask, flightAdminRoleAddTask);
    }
    else
    {
        LoggingUtilities.Logger.TraceInformation("Azure AD id does not exist for the security group: {0}.", securityGroupName);
        await this.CheckMembershipAndAddRole(FlightAdminSecurityGroupId, userId, FlightAdminRoleName).ConfigureAwait(false);
    }
}
else
{
    LoggingUtilities.Logger.TraceInformation("Security group name is not valid, checking for flight admin role for the user: {0}.", userAlias);
    await this.CheckMembershipAndAddRole(FlightAdminSecurityGroupId, userId, FlightAdminRoleName).ConfigureAwait(false);
}

// Add the flight privileged users role to be able to verify the user is authorized for the role.
string flightPrivilegedUsersRoleName = RoleRepository.Instance.GetByName(Constants.FlightPrivilegedUsersRoleKey).Name;
if (!this.roles.Contains(flightPrivilegedUsersRoleName, StringComparer.OrdinalIgnoreCase))
{
    LoggingUtilities.Logger.TraceInformation("Adding flight privileged users to roles list for the user: {0}.", userAlias);
    this.roles.Add(flightPrivilegedUsersRoleName);
}

if (userAlias != null)
{
    LoggingUtilities.Logger.TraceInformation("Check security group memberships and assign roles for the user: {0}.", userAlias);
    var newPrincipal = new GenericPrincipal(new GenericIdentity(userAlias), this.roles.ToArray());
    Thread.CurrentPrincipal = newPrincipal;
    HttpContext.Current.User = newPrincipal;
}

The recommendations about the following entries in the web.config entries did not help:

<system.web>
    <compilation debug="false" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" enableVersionHeader="false" requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,\,?" />
</system.web>
<appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>

Any recommendations on how to fix this would be appreciated.


Solution

  • Remove your .ConfigureAwait(false) calls. They are what causing you trouble. When you call .ConfigureAwait(false), it tells C# that you don't care which thread to use for the completion of async call. You end up in another thread that has doesn't have HttpContext.Current context, since it's a thread pool thread, not ASP.NET thread.