1
我有一個自定義授權屬性,它驗證頭中的令牌並設置用戶主體。.NET Web Api 2 UserPrincipal.IsAuthenticated在使用依賴注入(Unity)時始終爲false
//when token is validated
var userIdentityBase = new UserIdentityBase(token); <-- Inherited GenericIdentity
IPrincipal principal = new GenericPrincipal(userIdentityBase, null);
actionContext.Request.GetRequestContext().Principal = principal;
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
但是,當我注入的IPrincipal我的服務類,它不工作了,這工作得很好。 IsAuthenticated
是錯誤的。
統一設置代碼:
container.RegisterType<IPrincipal>(new InjectionFactory(u => HttpContext.Current.User));
注射時,它不工作(包括屏幕截圖採取withing相同的請求):
有什麼建議?
依賴關係解析程序正在解決應用程序啓動的依賴關係。在當時沒有當前用戶 –
@MarcusH,所以沒有辦法在運行時注入用戶主體? – Robert
我不認爲有,但我沒有事實來支持。我已經通過將用戶作爲參數或將靜態變量設置爲當前用戶來解決此問題。 –