gpt4 book ai didi

c# - 在 C# 中建立 SSL 连接时如何检查无效凭据

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:55 24 4
gpt4 key购买 nike

我有这个方法,它试图捕获在通过 SSL 连接时提供无效凭据时可能抛出的异常。凭据通过 SNMP 提供。但我并不总是能够将异常解释为无效凭据,正如您所看到的,我只是试图读取抛出异常的消息,该消息因设备而异。

我做的对吗?是否有任何万无一失的方法来检查建立连接所需的凭据是否有效?我完全迷失在这里,因为抛出的异常消息因设备而异。

感谢您的指点。

try
{
string ipSSL = string.Format(URL_CWIS_HELPSTRING, "s", SecurityBindingProxy.Destination.Address.Value.Host, "/");
System.Net.WebRequest https = System.Net.HttpWebRequest.Create(ipSSL);
System.Net.ServicePointManager.ServerCertificateValidationCallback = WsdlClient.ServiceRequirements.WsdlServiceRequirements.SSLCheckCallback;
https.Credentials = new System.Net.NetworkCredential(SNMP.ConnectionInfo.Instance.Username, SNMP.ConnectionInfo.Instance.Password); ;
System.Net.HttpWebResponse responseSSL = (System.Net.HttpWebResponse)https.GetResponse();
responseSSL.Close();
}
catch (Exception ex)
{
if (ex.Message.Contains("Unauthorized")
|| ex.Message.Contains("401"))
{
return -2;
}
}

最佳答案

您想捕获更具体类型的异常而不是解析异常消息。如果您查看 GetResponse 的文档您会看到记录了抛出的异常类型。如果您捕获到 WebException,那么这将允许您找出 HTTP 状态,而无需手动解析字符串,例如:

catch (System.Net.WebException ex)
{
var errorResponse = (System.Net.HttpWebResponse)ex.Response;
if (errorResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
//...
}
}

关于c# - 在 C# 中建立 SSL 连接时如何检查无效凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8758207/

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