C# 是否使用具有用户标识的QueueBackgroundWorkItem?

C# 是否使用具有用户标识的QueueBackgroundWorkItem?,c#,asp.net,impersonation,C#,Asp.net,Impersonation,根据Scott Hanselman的博客文章,我正在使用HostingEnvironment.QueueBackgroundWorkItem在ASP.Net应用程序的后台运行工作 我想以当前用户的身份运行后台任务。我尝试在操作中传递WindowsPrincipal并设置Thread.CurrentPrincipal,但这并没有导致操作以当前用户的身份执行 这是可能的,还是使用HostingEnvironment总是意味着以应用程序池身份运行 编辑 不完全是针对我最初的问题,但我也尝试通过Call

根据Scott Hanselman的博客文章,我正在使用
HostingEnvironment.QueueBackgroundWorkItem
在ASP.Net应用程序的后台运行工作

我想以当前用户的身份运行后台任务。我尝试在操作中传递WindowsPrincipal并设置Thread.CurrentPrincipal,但这并没有导致操作以当前用户的身份执行

这是可能的,还是使用HostingEnvironment总是意味着以应用程序池身份运行

编辑

不完全是针对我最初的问题,但我也尝试通过CallContext.LogicalSetData()和CallContext.LogicalGetData()传递一个值。在Get端,该值始终为null

编辑#2

还尝试在排队端执行此操作:

using (HostingEnvironment.Impersonate(windowsIdentity.Token))
{
     HostingEnvironment.QueueBackgroundWorkItem(work);
}

当工作实际完成时,操作中的当前WindowsIdentity仍然是应用程序池标识。

您“必须”使用“HostingEnvironment”的具体原因是什么

或者您是否尝试过使用WindowsImpersonationContext

System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = 
    ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

//Insert your code that runs under the security context of the authenticating user here.

impersonationContext.Undo();

您可以了解更多操作方法

当前用户的身份附加到处理请求的线程,并且仅在该请求的生存期内有效。即使将对
HttpContext.Current.User.Identity
的引用传递给工作者函数,您也会发现在尝试使用它时,它可能不再有效。据我所知,您需要使用Windows API进行一些工作,以克隆标识令牌,从而生成一个新的
WindowsIdentity
,然后可以在后台任务中使用它。比如说:

IntPtr copy = IntPtr.Zero,
    token = ((WindowsIdentity)HttpContext.Current.User.Identity).Token;
if (DuplicateToken(token, ref copy))  // the WinAPI function has more parameters, this is a hypothetical wrapper
{
    return new WindowsIdentity(copy);
}
// handle failure

将此
WindowsIdentity
传递给后台任务,并在需要时模拟它。不要忘记处理它。

文档中说“此重载方法不会将ExecutionContext或SecurityContext从调用者流向被调用者。因此,这些对象的成员(如CurrentPrincipal属性)不会从调用者流向被调用者。”请参阅问题中链接中的说明。如果AppDomain试图关闭,则必须按原样安排(帮助)以防止线程被终止。