等待调用后,异步中的HttpContext.Current为null

时间:2015-09-23 04:52:41

标签: c# asp.net-web-api async-await httpcontext

等待调用后,异步中的HttpContext.Current为null。

这是我的代码:

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;
}

有关web.config条目中以下条目的建议没有帮助:

<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>

任何有关如何解决此问题的建议都将受到赞赏。

1 个答案:

答案 0 :(得分:4)

删除.ConfigureAwait(false)来电。它们是导致你麻烦的原因。当你调用.ConfigureAwait(false)时,它告诉C#你不关心用于完成异步调用的线程。你最终在另一个没有HttpContext.Current上下文的线程中,因为它是一个线程池线程,而不是ASP.NET线程。