10

在身份验证期间使用 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在恢复同步上下文时不会丢弃该突变?

4

1 回答 1

11

你也必须设置HttpContext.Current.User。有关更多信息,请参阅此答案此博客文章

更新:还要确保您在 .NET 4.5 上运行并UserTaskFriendlySynchronizationContext设置为true.

于 2013-05-14T21:04:50.460 回答