简体   繁体   English

C#UserPrincipal对象引用未设置为对象的实例

[英]C# UserPrincipal Object reference not set to an instance of an object

I am receiving the classic, Object reference not set to an instance of an object in my project when viewing the hosted website. 查看托管网站时,我收到的经典Object reference not set to an instance of an object我项目中Object reference not set to an instance of an object Works when building a debug version locally. 在本地构建调试版本时有效。

Live 生活

Example of code that is showing error message: 显示错误消息的代码示例:

     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);
                }
            }

Try this: 尝试这个:

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);
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM