gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:53:16 25 4
gpt4 key购买 nike

在查看托管网站时,我在我的项目中收到经典的对象引用未设置为对象的实例。在本地构建调试版本时有效。

直播

显示错误消息的代码示例:

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

最佳答案

试试这个:

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

关于C# UserPrincipal 对象引用未设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13115836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com