在模拟之前和在代码后面的ASP.NET中模拟之后获取IIS用户

时间:2014-02-05 10:41:31

标签: asp.net iis .net-4.0 impersonation username

我在我的网站中使用impersonate,我需要将每个请求记录到网站,因此也需要用户名,我想我们可以在服务器变量中获取此信息,但Auth_UserLogOn_User都返回空字符串。如何在模仿之前和模仿之后获取用户名?有人有任何想法吗?

1 个答案:

答案 0 :(得分:0)

使用HttpContext.Current.User.Identity

WindowsIdentity wId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsIdentity wIdb4 = WindowsIdentity.GetCurrent();
string name = wIdb4.Name;
Response.Write("Before impersonation"+name +"<br>");// <-- Writes ASPNET Account


//Till this line,code is executed in the context of worker process
WindowsImpersonationContext wIdCon = wId.Impersonate();
WindowsIdentity wIdafter = WindowsIdentity.GetCurrent();
name = wIdafter.Name;
Response.Write("After Impersonation " + name + "<br>");// <-- writes Logged in user

//Run in the context of logged authenticated user, do your //operations that require impersonation

wIdCon.Undo();
WindowsIdentity wIdafterUndo = WindowsIdentity.GetCurrent();
name = wIdafterUndo.Name;

Response.Write("After undo Impersonation " + name + "<br>");

OUTPUT
Before impersonation SERVER\ASPNET
After Impersonation TestAccount
After undo Impersonation SERVER\ASPNET