gpt4 book ai didi

c# - 一般异常处理问题

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:54 26 4
gpt4 key购买 nike

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

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

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

enter image description here

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

enter image description here

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

如何做到这一点?

最佳答案

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

The ValidateCredentials method binds to the server specified in the constructor. If the username and password parameters are null, the credentials specified in the constructor are validated. If no credential were specified in the constructor, and the username and password parameters are null, this method validates the default credentials for the current principal.

所以你需要做的就是

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

}
}

关于c# - 一般异常处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19909652/

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