![](/img/trans.png)
[英]Custom SynchronizationContext to set Thread.CurrentPrincipal asynchronously in unittest
[英]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
不會丟棄該突變?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.