简体   繁体   English

设置Thread.CurrentPrincipal异步?

[英]Set Thread.CurrentPrincipal Asynchronously?

Using ASP.NET WebAPI, during authentication, Thread.CurrentPrincipal is set so that controllers can later use the ApiController.User property. 使用ASP.NET WebAPI,在身份验证期间,设置Thread.CurrentPrincipal ,以便控制器稍后可以使用ApiController.User属性。

If that authentication step becomes asynchronous (to consult another system), any mutation of CurrentPrincipal is lost (when the caller's await restores the synchronization context). 如果该身份验证步骤变为异步(以咨询另一个系统),则会丢失CurrentPrincipal任何突变(当调用者await恢复同步上下文时)。

Here's a very simplified example (in the real code, authentication happens in an action filter): 这是一个非常简化的示例(在实际代码中,身份验证发生在动作过滤器中):

using System.Diagnostics;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;

public class ExampleAsyncController : System.Web.Http.ApiController
{
    public async Task GetAsync()
    {
        await AuthenticateAsync();

        // The await above saved/restored the current synchronization
        // context, thus undoing the assignment in AuthenticateAsync(). 
        Debug.Assert(User is GenericPrincipal);
    }

    private static async Task AuthenticateAsync()
    {
        // Save the current HttpContext because it's null after await.
        var currentHttpContext = System.Web.HttpContext.Current;

        // Asynchronously determine identity.
        await Task.Delay(1000);
        var identity = new GenericIdentity("<name>");

        var roles = new string[] { };
        Thread.CurrentPrincipal = new GenericPrincipal(identity, roles);
        currentHttpContext.User = Thread.CurrentPrincipal;
    }
}

How do you set Thread.CurrentPrincipal in an async function such that the caller's await doesn't discard that mutation when restoring the synchronization context? 如何在异步函数中设置Thread.CurrentPrincipal ,以便在恢复同步上下文时调用者的await不会丢弃该突变?

You have to set HttpContext.Current.User as well. 您还必须设置HttpContext.Current.User See this answer and this blog post for more info. 有关详细信息,请参阅此答案此博客文章

Update: Also ensure you are running on .NET 4.5 and have UserTaskFriendlySynchronizationContext set to true . 更新:还要确保您在.NET 4.5上运行并将UserTaskFriendlySynchronizationContext设置为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM