使用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
在恢复同步上下文时不会丢弃该变化?
DelegatingHandler
,它可以在到达控制器之前进行身份验证。 - Matthew