我正在使用ASP.Net Web API 2 / .Net 4.5.2.
Thread.CurrentPrincipal = callingPrincipal;
但是当我这样做时,我得到一个ObjectDisposedException:
System.ObjectDisposedException: Safe handle has been closed
如何将当前主体保留在后台工作项中?
我可以以某种方式复制校长吗?
public void Run<T>(Action<T> action) { _logger.Debug("Queueing background work item"); var callingPrincipal = Thread.CurrentPrincipal; HostingEnvironment.QueueBackgroundWorkItem(token => { try { // UNCOMMENT - THROWS EXCEPTION // Thread.CurrentPrincipal = callingPrincipal; _logger.Debug("Executing queued background work item"); using (var scope = DependencyResolver.BeginLifetimeScope()) { var service = scope.Resolve<T>(); action(service); } } catch (Exception ex) { _logger.Fatal(ex); } finally { _logger.Debug("Completed queued background work item"); } }); }
解决方法
事实证明,ClaimsPrincipal现在有一个复制构造函数.
var principal = new ClaimsPrincipal(Thread.CurrentPrincipal);
这似乎可以在保留所有身份和声明信息的同时解决问题.完整的功能如下:
public void Run<T>(Action<T> action) { _logger.Debug("Queueing background work item"); var principal = new ClaimsPrincipal(Thread.CurrentPrincipal); HostingEnvironment.QueueBackgroundWorkItem(token => { try { Thread.CurrentPrincipal = principal; _logger.Debug("Executing queued background work item"); using (var scope = DependencyResolver.BeginLifetimeScope()) { var service = scope.Resolve<T>(); action(service); } } catch (Exception ex) { _logger.Fatal(ex); } finally { _logger.Debug("Completed queued background work item"); } }); }