2012-10-29 80 views
2

我在查看託管網站時收到了項目中的經典代碼Object reference not set to an instance of an object。在本地構建調試版本時工作。未將C#UserPrincipal對象引用設置爲對象的實例

的代碼,該代碼表示​​錯誤消息直播

實施例:

 using System.DirectoryServices.AccountManagement; 
    protected void Page_Load(object sender, EventArgs e) 
      { 
       try 
       { 

        String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name; 
        username = username.Substring(3); 
        PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc"); 
        UserPrincipal user = UserPrincipal.FindByIdentity(pc, username); 
        string NTDisplayName = user.DisplayName; 
        //String NTUser = user.SamAccountName; 
        lblntuser.Text = NTDisplayName; 

       } 
       catch (Exception Ex) 
       { 
        lblntuser.Text = Ex.Message; 
        System.Diagnostics.Debug.Write(Ex.Message); 
       } 
      } 
+3

在其上線?通過調試程序... –

+1

你確定WindowsIdentity.GetCurrent()返回一個非空值嗎? –

+0

@FyodorSoikin釘在頭上。它正在使用我的網絡服務器的NT AUTHORITY \ NETWORK SERVICE,這與正在瀏覽頁面的用戶不同。 – goingsideways

回答

1

嘗試這種情況:

protected void Page_Load(object sender, EventArgs e) 
{ 
    try 
    { 
     // you need to also take into account that someone could get to your 
     // page without having a Windows account.... check for NULL ! 
     if (System.Security.Principal.WindowsIdentity == null || 
      System.Security.Principal.WindowsIdentity.GetCurrent() == null) 
     { 
      return; // possibly return a message or something.... 
     } 

     String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name; 

     // if the user name returned is null or empty -> abort 
     if(string.IsNullOrEmpty(username)) 
     { 
      return; 
     } 

     username = username.Substring(3); 

     PrincipalContext pc = new PrincipalContext(ContextType.Domain, "dc"); 

     UserPrincipal user = UserPrincipal.FindByIdentity(pc, username); 

     // finding the user of course can also fail - check for NULL !! 
     if (user != null) 
     { 
      string NTDisplayName = user.DisplayName; 
      //String NTUser = user.SamAccountName; 
      lblntuser.Text = NTDisplayName; 
     } 
    } 
    catch (Exception Ex) 
    { 
     lblntuser.Text = Ex.Message; 
     System.Diagnostics.Debug.Write(Ex.Message); 
    } 
} 
相關問題