1、模拟 IIS验证的帐户或用户
若要在收到 ASP.NET 应用程序中每个页的每个请求时模拟Microsoft Internet 信息服务 (IIS) 身份验证用户,必须在此应用程序的 Web.config 文件中包含<identity> 标记,并将 impersonate 属性设置为true
目前我找到的解决方法是通过System.Security.Principal.WindowsIdentity.Impersonate方法在子线程里模拟主线程的“windows账户标记”从而获得和主线程相同权限。下面是一段测试代码:
- protected void Page_Load(object sender, EventArgs e)
- {
- //先获得页面执行的主线程用户信息, 悟空注释,悟空的博客 www.7es.cn
- System.Security.Principal.WindowsIdentity obj = System.Security.Principal.WindowsIdentity.GetCurrent();
- thread = new Thread(new ParameterizedThreadStart(proc));
- thread.Start(obj);
- }
- void proc(object obj)
- {
- System.Security.Principal.WindowsIdentity wi = (System.Security.Principal.WindowsIdentity)obj;
- try
- {
- log.Write("test 0 start" + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
- }
- catch (Exception ex)
- {
- System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt",
- "这里可能无法写入日志,会访问错误异常的,只是表示一下此处没有权限写入,后面模拟账号之后才能获得权限");
- }
- System.Security.Principal.WindowsIdentity.Impersonate(wi.Token); //模拟一下
- System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt",
- "ok, 这里可以写入日志文件");
- }