将主体保留在排队的后台工作项中 [英] Retaining principal inside queued background work item
问题描述
我正在使用ASP.Net Web API 2/.Net 4.5.2.
I'm using ASP.Net Web API 2 / .Net 4.5.2.
我在排队后台工作项时试图保留调用主体.为此,我正在尝试:
I'm trying to retain the calling principal when queueing a background work item. To that end, I'm trying to:
Thread.CurrentPrincipal = callingPrincipal;
但是,当我这样做时,我得到一个ObjectDisposedException:
But when I do so, I get an ObjectDisposedException:
System.ObjectDisposedException:安全句柄已关闭
System.ObjectDisposedException: Safe handle has been closed
如何将当前主体保留在后台工作项中?
我可以以某种方式复制校长吗?
How do I keep the current principal inside the background work item?
Can I make a copy of the principal somehow?
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
现在具有副本构造函数.
Turns out ClaimsPrincipal
now has a copy constructor.
var principal = new ClaimsPrincipal(Thread.CurrentPrincipal);
这似乎可以解决问题,同时保留所有身份和索偿信息.完整的功能如下:
This appears to resolve the issue while retaining all of the identity and claims information. The complete function follows:
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");
}
});
}
这篇关于将主体保留在排队的后台工作项中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!