提问人:Rafael 提问时间:5/5/2023 更新时间:5/6/2023 访问量:36
从回调方法内部填充类变量
Populate class variable from inside callback method
问:
我在.NET中有一个包含回调的方法。回调无法命中函数外的方法,如何调试回调方法?
这是我的方法
public string ChainStatusLog { get; set; }
public GPayService(IConfiguration configuration, IOptions<GpayConfiguration> gPayConfiguration, BlobService blobService)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//Get Certificate
CaCert = GetPemCertificate(blobService);
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
return true;
if (sslPolicyErrors != 0 && System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors != 0)
{
X509Chain caChain = new X509Chain();
caChain.ChainPolicy.ExtraStore.Add(CaCert);
caChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
caChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
caChain.Build(new X509Certificate2(certificate));
ChainStatusLog = GetChainStatusMessage(caChain.ChainStatus);
if (caChain.ChainStatus.Any(status => status.Status != X509ChainStatusFlags.UntrustedRoot))
{
foreach (X509ChainStatus chainStatus in caChain.ChainStatus)
{
if (chainStatus.Status == X509ChainStatusFlags.UntrustedRoot)
{
return true;
}
}
}
if (caChain.ChainStatus.Length == 0)
return false;
return caChain.ChainStatus[0].Status == X509ChainStatusFlags.NoError || caChain.ChainStatus[0].Status == X509ChainStatusFlags.PartialChain;
}
else
return false;
};
}
public static string GetChainStatusMessage(X509ChainStatus[] chainStatus)
{
if (chainStatus == null || chainStatus.Length == 0)
{
return "";
}
StringBuilder sb = new StringBuilder();
foreach (var status in chainStatus)
{
sb.AppendLine($"Status: {status.Status}, Status Information: {status.StatusInformation}");
}
return sb.ToString();
}
在 GetChainStatusMessage(X509ChainStatus[] chainStatus) 方法上设置的断点永远不会命中,因此 ChainStatusLog 类变量始终为 null。
答:
1赞
Johan van Tonder
5/6/2023
#1
我认为您可能在“”符号之前缺少一个“”符号,您将事件处理程序方法分配给委托属性,即.+
=
ServerCertificateValidationCallback
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors)
此语法用于多播委托,允许您将多个事件处理程序组合到一个委托上。请注意,尽管是多播委托,但只有最后一个处理程序的返回值是权威的。更多信息在这里: https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback?view=net-6.0RemoteCertificateValidationCallback
评论
0赞
Rafael
5/6/2023
谢谢约翰,我会在周一尝试你的建议
0赞
Rafael
5/9/2023
Johan 不幸的是,这不起作用,回调函数中的类变量仍然具有 null 值
0赞
Rafael
5/12/2023
嗨,Johan,这里的问题是 ServicePointManager.ServerCertificateValidationCallback 在 .NET 6.0 中已被弃用,这就是它不起作用的原因。解决方法是在 http 客户端上放置一个不同的回调
评论