本文介绍了设置异步Thread.CurrentPrincipal中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Using ASP.NET WebAPI, during authentication, Thread.CurrentPrincipal is set so that controllers can later use the ApiController.User property.

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

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

下面是一个非常简单的例子(在真实code,认证一个动作过滤器发生):

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

如何在异步功能,使主叫方的伺机不丢弃设置 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?

推荐答案

您必须设置 HttpContext.Current.User 为好。见this回答和this博客文章获取更多信息。

You have to set HttpContext.Current.User as well. See this answer and this blog post for more info.

更新:同时确保你在.NET 4.5上运行,并已 UserTaskFriendlySynchronizationContext 设置为真正

Update: Also ensure you are running on .NET 4.5 and have UserTaskFriendlySynchronizationContext set to true.

这篇关于设置异步Thread.CurrentPrincipal中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 00:35