IIS中子線程對文件的讀寫的權限問題解決方案

 
1、模擬 IIS驗證的帳戶或用戶

若要在收到 ASP.NET 應用程序中每個頁的每個請求時模擬Microsoft Internet 信息服務 (IIS) 身份驗證用戶,必須在此應用程序的 Web.config 文件中包含<identity> 標記,並將 impersonate 屬性設置爲true

目前我找到的解決方法是通過System.Security.Principal.WindowsIdentity.Impersonate方法在子線程裏模擬主線程的“windows賬戶標記”從而獲得和主線程相同權限。下面是一段測試代碼:

 
  1. protected void Page_Load(object sender, EventArgs e)
  2. {   
  3.     //先獲得頁面執行的主線程用戶信息, 悟空註釋,悟空的博客 www.7es.cn    
  4.     System.Security.Principal.WindowsIdentity obj = System.Security.Principal.WindowsIdentity.GetCurrent();
  5.     thread = new Thread(new ParameterizedThreadStart(proc));
  6.     thread.Start(obj);
  7. }
  8.  
  9. void proc(object obj)
  10. {
  11.     System.Security.Principal.WindowsIdentity wi = (System.Security.Principal.WindowsIdentity)obj;
  12.     
  13.     try
  14.     {
  15.         log.Write("test 0 start" + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
  16.     }
  17.     catch (Exception ex)
  18.     {
  19.       System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt"
  20.       "這裏可能無法寫入日誌,會訪問錯誤異常的,只是表示一下此處沒有權限寫入,後面模擬賬號之後才能獲得權限");
  21.     }
  22.     
  23.     System.Security.Principal.WindowsIdentity.Impersonate(wi.Token); //模擬一下
  24.     
  25.     System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt"
  26.       "ok, 這裏可以寫入日誌文件");
  27. }
這只是手寫的測試代碼,可能有出入手誤的地方,具體自己根據代碼自己修改吧。某些情況下可能還需要web.config裏進行一些修改,當然,如果可以配置iis的話,這些問題都不用考慮了,完全可以通過iis配置給更高的權限解決讀寫文件問題。

2、爲 ASP.NET應用程序的所有請求模擬特定用戶

   若要爲 ASP.NET 應用程序的所有頁面上的所有請求模擬特定用戶,可以在該應用程序的 Web.config 文件的<identity> 標記中指定 userName 和 password屬性。例如:
<identity impersonate="true"userName="accountname" password="password"/>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章