簡體   English   中英

設置Thread.CurrentPrincipal異步?

[英]Set Thread.CurrentPrincipal Asynchronously?

使用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不會丟棄該突變?

您還必須設置HttpContext.Current.User 有關詳細信息,請參閱此答案此博客文章

更新:還要確保您在.NET 4.5上運行並將UserTaskFriendlySynchronizationContext設置為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM