Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 一般异常处理问题_C#_.net_Exception_Exception Handling_Active Directory - Fatal编程技术网

C# 一般异常处理问题

C# 一般异常处理问题,c#,.net,exception,exception-handling,active-directory,C#,.net,Exception,Exception Handling,Active Directory,我正在使用Active Directory API,并尝试使用以下代码连接到服务器: PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword); 每当传递无效的登录用户名或密码时,不会引发整个语句中的异常,但以下代码将继续执行。在调试时,我发现PrincipalContext类抛出了一个错误,如

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

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, (server + ":" + port), loginUsername, loginPassword);
每当传递无效的登录用户名或密码时,不会引发整个语句中的异常,但以下代码将继续执行。在调试时,我发现
PrincipalContext
类抛出了一个错误,如下所示:

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

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


如何做到这一点?

System.DirectoryServices.AccountManagement的类在执行时是不同的。在必须连接到Active Directory服务器之前,它不会尝试连接到Active Directory服务器。该方法是从MSDN强制检查的方法:

ValidateCredentials方法绑定到中指定的服务器 构造器。如果用户名和密码参数为空,则 将验证构造函数中指定的凭据。如果没有 在构造函数中指定了凭据,以及用户名和 密码参数为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);

    }
}

一个基本的捕获不起作用?比如:

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

我发现,尝试将PrincipalContext.ConnectedServer属性分配给变量会导致异常出现:

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

处理主体上下文中的任何异常的最佳方法是将代码放在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;                    

       }
string user=txtUsername.Text;
字符串pass=txtPassword.Text;
//开始一个尝试和捕捉方法
尝试
{
//创建principalcontext对象
var pc=new PrincipalContext(ContextType.Domain,*******,user,pass);
{
//验证用户凭据
if(pc.ValidateCredentials(用户,通过))
{
//创建用户标识
UserPrincipal userp=UserPrincipal.FindByIdentity(pc,IdentityType.SamAccountName,用户);
//检查是否返回了用户
if(userp!=null)
{
//如果用户存在,则返回授权组数组
var grps=userp.GetAuthorizationGroups();
//将数组转换为列表以启用对CI组的搜索
List strList=grps.Select(o=>o==null?String.Empty:o.ToString()).ToList();
//从列表中检查CI组
如果(strList.Contains(“CISS”))
{
//创建一个会话变量以显示loggedin用户,并将错误面板设置为false
会话[“用户名”]=用户;
ErrorPanel.Visible=false;
//将用户重定向到主页
重定向(“appdesk/account.aspx”);
}
如果(!strList.Contains(“CISS”))
{
Label1.Text=“您没有登录平台的权限”;
ErrorPanel.Visible=true;
}
}
//如果用户凭据无效
如果(!pc.ValidateCredentials(用户,通过))
{
Label1.Text=“登录失败。用户名或密码不正确”;
ErrorPanel.Visible=true;
}
}
}
//在try中捕获异常
捕获(异常exc)
{
Label1.Text=exc.Message.ToString();
ErrorPanel.Visible=true;
}

我的主要问题是,我不仅要验证用户名和密码,还要确保相应的帐户具有连接到Active Directory所需的凭据。请参考我之前的问题,了解我试图完成的内容。我没有得到任何帮助,因此我将继续关于这一点,我在网上找不到任何直接的解释:是的,这就是它的作用。如果你看到
//这里的其余代码
,你已经确认1)服务器在
(服务器+:“+端口)
正在响应,2)凭据
loginUsername,loginPassword
具有与服务器通信的权限。因此,查看您以前的问题,您可以将管理员的用户名和密码传递到
loginUsername
loginPassword
ValidateCredentials
方法r如果正在传递的帐户没有足够的凭据访问ActiveDirectory,则返回false?我询问的原因是,作为我正在创建的应用程序的一部分,我创建了一个验证用户凭据的方法,即仅检查其用户名和密码是否正确。为此,我使用ValidateCredentials方法-但是帐户可以是存储在AD数据库中的任何帐户,因此它们可能是权限较低的帐户。在这些情况下,它不起作用吗?如果是,还有其他方法吗?请注意,我正在传入
null,null
以验证ediantals,这使得它可以验证您传入
PrincipalContext的凭据
。是的,这些权限可能是没有权限执行您想要执行的操作(如创建新用户或诸如此类)的用户