我正在使用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"); } }); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。