使用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
恢复同步上下文时不会丢弃突变?