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

时间:2016-10-11 20:40:17

标签: asp.net-mvc error-handling asp.net-mvc-5 active-directory userprincipal

尝试按如下方式设置自定义用户检查:

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帐户或移动设备时会发生什么?

我如何在这里发现错误?

1 个答案:

答案 0 :(得分:0)

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

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