设置异步Thread.CurrentPrincipal中?(Set Thread.CurrentPr

2019-09-03 05:21发布

使用ASP.NET的WebAPI,认证过程中, Thread.CurrentPrincipal设置,使控制器可以在以后使用ApiController.User属性。

如果验证步骤变得异步(咨询其他系统)的任何突变CurrentPrincipal丢失(当来电await恢复同步的情况下)。

这里是一个非常简单的例子(在真实的代码,验证在行动过滤器发生):

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

如何设置Thread.CurrentPrincipal的异步功能使得呼叫者的await恢复同步上下文时不会丢弃突变?

Answer 1:

你必须设置HttpContext.Current.User为好。 见这个答案和这个博客帖子获取更多信息。

更新:此外,还要确保你在.NET 4.5运行,并有UserTaskFriendlySynchronizationContext设置为true



文章来源: Set Thread.CurrentPrincipal Asynchronously?