一般异常处理问题

时间:2013-11-11 15:14:14

标签: c# .net exception exception-handling active-directory

我正在使用Active Directory API,并尝试使用以下代码连接到服务器:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword);

每当传递无效的登录用户名或密码时,不会抛出整个语句的异常,但以下代码将继续执行。在调试时,我发现PrincipalContext类会引发错误,如下所示:

enter image description here

这是类中包含的两个属性。在进一步检查“ConnectedServer”属性时,调试器中将显示以下内容:

enter image description here

我的问题是,由于外部没有抛出错误,我不确定如何实际检查此错误。如果用户名或密码无效,我想显示一条简单的错误消息 - 基本上找到一种方法来检查是否已抛出上述错误。

如何做到这一点?

4 个答案:

答案 0 :(得分:1)

System.DirectoryServices.AccountManagement的类是不同的执行。它不会尝试连接到Active Directory服务器。 ValidateCredentials方法是强制检查的方法,来自MSDN:

  

ValidateCredentials方法绑定到中指定的服务器   构造函数。如果用户名和密码参数为null,则为   验证构造函数中指定的凭据。如果不   凭证在构造函数中指定,用户名和   password参数为null,此方法验证默认值   当前校长的证书。

所以你需要做的就是

using(PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword))
{
    //This will force the connection to the server and validate that the credentials are good
    //If the connection is good but the credentals are bad it will return "false", if the connection is bad it will throw a exception of some form.
    if(principalContext.ValidateCredentials(null, null))
    {
        // Rest of code here.

        //This is how you do the same check you where doing in your previous quesiton, notice that this is "userName", and "password" not "loginUsername" and "loginPassword"
        valid = principalContext.ValidateCredentials(userName,password);

    }
}

答案 1 :(得分:0)

基本捕获不起作用?类似的东西:

private ADConnectResults Connect(string server, int port)
try
{
    PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword);
    return new ADConnectResults(true, principalContext);
}
catch(DirectoryServicesCOMException dex)
{
     Log(dex);
     return new ADConnectResults(false);
}
}

答案 2 :(得分:0)

我发现尝试将PrincipalContext.ConnectedServer属性分配给变量允许异常浮出水面:

using(var _ctx = new PrincipalContext(ContextType.Domain, server + ":" + port))
{
   try
   {
      var connectedServer = _ctx.ConnectedServer;
   }
   catch (Exception)
   {
      //do something with the caught exception
   }
}

答案 3 :(得分:0)

处理主要上下文中的任何异常的最佳方法是将代码置于try中,然后捕获异常,如下所示。

        string user = txtUsername.Text;
        string pass = txtPassword.Text;

        //start a try and catch method
      try
      {

       //create a principalcontext object

        var pc = new PrincipalContext(ContextType.Domain, "*****", user, pass);
         {


               //validate the user credentials
                if (pc.ValidateCredentials(user, pass))
                {
                    //create a user identity
                    UserPrincipal userp = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, user);

                    //check if the user is returned

                    if (userp != null)
                    {
                        //if user exists, return an array of authorized groups
                        var grps = userp.GetAuthorizationGroups();

                        //convert the array to a list to enable search of CIS group
                        List<string> strList = grps.Select(o => o == null ? String.Empty : o.ToString()).ToList();

                        //check for CIS group from the list
                        if (strList.Contains("CISS"))
                        {
                            //create a session variable to show the loggedin user and set the error panel to false
                            Session["username"] = user;
                            ErrorPanel.Visible = false;

                            //redirect the user to the homepage
                            Response.Redirect("appdesk/account.aspx");
                        }
                        else if (!strList.Contains("CISS"))
                        {
                            Label1.Text = "You Don't have the Rights to login to the platfrom";
                            ErrorPanel.Visible = true;

                    }
                }
                 //if the user credentials are invalid
                if (!pc.ValidateCredentials(user, pass))
                {
                    Label1.Text = "Login Failed.Incorrect Username or Password";
                    ErrorPanel.Visible = true;


                }
             }
        }
          //catch the exceptions in the try
       catch (Exception exc)
       {
                Label1.Text = exc.Message.ToString();
                ErrorPanel.Visible = true;                    

       }