Dot-Net
使用impersonate=true時如何在IIS中獲取目前應用程序池使用者?
在 .net 中,當一個網站託管在 IIS 中時,如何獲取該網站正在執行的目前使用者。即應用程序池使用者不是訪問該站點的目前使用者。
使用 windows 集成和模擬。
<authentication mode="Windows"/> <identity impersonate="true"/>
要在託管程式碼中恢復為應用程序池使用者,您可以執行以下操作:
using (WindowsIdentity.Impersonate(IntPtr.Zero)) { //This code executes under app pool user }
找到了解決方案。
使用 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; }