在ASP.NET后台代码中,在模拟前和模拟后获取IIS用户

在ASP.NET后台代码中,在模拟前和模拟后获取IIS用户,asp.net,iis,.net-4.0,impersonation,Asp.net,Iis,.net 4.0,Impersonation,我在我的站点中使用impersonate,我需要记录每个到站点的请求,所以也需要用户名,我认为我们可以在服务器变量中获得它,但是Auth\u User和LogOn\u User都返回空字符串。如何在模拟前和模拟后获取用户名?有人有什么想法吗?使用 WindowsIdentity wId=(WindowsIdentity)HttpContext.Current.User.Identity; WindowsIdentity wIdb4=WindowsIdentity.GetCurrent(); 字符

我在我的站点中使用impersonate,我需要记录每个到站点的请求,所以也需要用户名,我认为我们可以在服务器变量中获得它,但是
Auth\u User
LogOn\u User
都返回空字符串。如何在模拟前和模拟后获取用户名?有人有什么想法吗?

使用

WindowsIdentity wId=(WindowsIdentity)HttpContext.Current.User.Identity;
WindowsIdentity wIdb4=WindowsIdentity.GetCurrent();
字符串名称=wIdb4.name;
响应。写入(“模拟前”+name+“
”//
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