2010-04-30 31 views
8

在.net中,当一个网站托管在IIS中时,您如何获取该网站正在运行的当前用户。即应用程序池用户不是当前访问该站点的用户。如何在使用impersonate = true时在IIS中获取当前应用程序池用户?

使用windows集成和模拟。

<authentication mode="Windows"/> 
<identity impersonate="true"/> 
+0

用于什么?如果您需要获取应用程序池用户的某些操作,那么您的模拟架构可能不正确。 – 2010-04-30 01:11:25

回答

18

要恢复到应用程序池的用户在托管代码中,你可以做到以下几点:

using (WindowsIdentity.Impersonate(IntPtr.Zero)) 
{ 
    //This code executes under app pool user 
} 
+0

[快速链接](https://msdn.microsoft.com/en-us/library/chf6fbt4(v = vs.110).aspx#remarksToggle)到相关文档。 – 2015-01-30 09:26:34

0

如果你纯粹需要看到用户,那么你不能只使用Environment.UserName?

我刚刚重新配置我的环境,使其与经典应用程序池(模拟)一起运行,并且用户使用Impersonate作为IUSR出现。

+0

我实际上希望WindowsIdentity不是用户名 – Simon 2010-05-10 06:14:48

2

找到了解决方案。

使用RevertToSelf,您可以从线程中去除模拟。在IIS中,这相当于App Pool用户。

一些DOCO

http://www.pinvoke.net/default.aspx/advapi32.reverttoself

http://msdn.microsoft.com/en-us/library/aa379317%28VS.85%29.aspx

和代码

[DllImport("advapi32.dll", SetLastError = true)] 
    static extern bool RevertToSelf(); 

    private static WindowsIdentity GetAppPoolIdentity() 
    { 
     WindowsIdentity identity = null; 
     Win32Exception win32Exception = null; 
     var thread = new Thread(o => 
         { 
          if (!RevertToSelf()) 
          { 
           var win32error = Marshal.GetLastWin32Error(); 
           win32Exception = new Win32Exception(win32error); 
          } 

          identity = WindowsIdentity.GetCurrent(); 
         }); 
     thread.Start(); 
     thread.Join(); 
     if (win32Exception != null) 
     { 
      throw win32Exception; 
     } 
     return identity; 
    } 
+0

也许使用**'this.Request.LogonUserIdentity.Name' ** – Kiquenet 2015-12-09 11:34:46

0

John Simons:正是我想要的,谢谢。 对于VB.net版本:

With System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero) 
    Dim sCurrentUserName As String = System.Security.Principal.WindowsIdentity.GetCurrent.Name 
End With 
相关问题