当您从非 AD 帐户调用 UserPrincipal.Current.GivenName 时会发生什么?

What happens when you call UserPrincipal.Current.GivenName from a non AD account?

正在尝试设置自定义用户检查,如下所示:

currentSessionUser = new User() //Nope, lets pull information from the Active Directory
{
    FirstName = UserPrincipal.Current.GivenName,
    LastName = UserPrincipal.Current.Surname,
    Username = UserPrincipal.Current.SamAccountName,
    AccountState = 0
};

当您的客户端是非 AD 帐户或移动设备时会发生什么情况?

如何捕获此处的错误?

要正确捕获可能抛出的异常- PrincipalServerDownException 您只需要将试图查询 userprincipal 的区域封装在 catch 块中以获取上述异常类型。

    try
    {
        u = new User
        {
            FirstName = UserPrincipal.Current.GivenName,
            LastName = UserPrincipal.Current.Surname,
            Username = UserPrincipal.Current.SamAccountName,
            Guid = UserPrincipal.Current.Guid.ToString(),
            CanEditHidData = true,
            CanEditQaData = true,
            AccountState = 0 //0=Unlocked 1=HigherPrivs Privs 2=Locked
        };
        return u;
    }
    catch (PrincipalServerDownException e)
    {
        u = new User
        {
            FirstName = "Guest",
            LastName = "Account",
            Username = "guest",
            Guid = Guid.Empty.ToString(),
            CanEditHidData = false,
            CanEditQaData = false,
            AccountState = 3 //0=Unlocked 1=HigherPrivs Privs 2=Locked 3=Guest
        };
        ViewBag.ErrorMessage = e.Message;
        View("Error");
        return u;
    }