我正在运行一个自托管网络服务。通信通过 https 进行,我使用的是自签名服务器证书。端口是可变的。因此,在每个应用程序启动时,我都会在存储中查找证书并将其绑定(bind)到特定端口。我正在使用 netsh 和删除/添加来完成此操作。
有没有办法查明命令“http add sslcert ipport=0.0.0.0:{port}”是否已由应用程序启动之前执行过?所以我不必在每个应用程序启动时删除并添加它。 我的想法是调用“http show sslcert ipport=0.0.0.0:{port}”并查看输出。但这不太好.. 那么是否有 C# 方法可以执行此操作?
public static bool ActivateCertificate(int port, X509Certificate2 certificate, string appId)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
bool certificateExists = false;
store.Open(OpenFlags.ReadWrite);
try
{
foreach (var cert in store.Certificates)
{
if (cert.Thumbprint != null && cert.Thumbprint.Equals(certificate.Thumbprint, StringComparison.InvariantCultureIgnoreCase))
{
certificateExists = true;
break;
}
}
if (!certificateExists)
{
store.Add(certificate);
}
}
catch (Exception ex)
{
Log.Error(ex, "Could not activate certificate!");
return false;
}
finally
{
store.Close();
}
StringBuilder str = new StringBuilder();
ProcessStartInfo psi = new ProcessStartInfo() {CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true};
psi.FileName = "netsh";
psi.Arguments = $"http show sslcert ipport=0.0.0.0:{port}";
Process procShow = Process.Start(psi);
while (procShow != null && !procShow.StandardOutput.EndOfStream)
{
str.Append(procShow.StandardOutput.ReadLine());
}
Log.Warn(str.ToString);
// delete IPV4.
psi.Arguments = $"http delete sslcert ipport=0.0.0.0:{port}";
Process procDel = Process.Start(psi);
//exitCode = procDel.ExitCode;
while (procDel != null && !procDel.StandardOutput.EndOfStream)
{
str.Append(procDel.StandardOutput.ReadLine());
}
Log.Warn(str.ToString);
procDel?.WaitForExit(1000);
// IPV4-Adresse hinzufügen.
psi.Arguments = $"http add sslcert ipport=0.0.0.0:{port} certhash={certificate.Thumbprint.ToLower()} appid={{{appId}}}";
Process proc = Process.Start(psi);
//exitCode = proc.ExitCode;
while (proc != null && !proc.StandardOutput.EndOfStream)
{
str.Append(proc.StandardOutput.ReadLine());
}
/*
// delete IPV6
Log.Warn(str.ToString);
proc?.WaitForExit(1000);
psi.Arguments = $"http delete sslcert ipport=[::]:{port}";
Process procDelV6 = Process.Start(psi);
while (procDelV6 != null && !procDelV6.StandardOutput.EndOfStream)
{
str.Append(procDelV6.StandardOutput.ReadLine());
}
Log.Warn(str.ToString);
procDelV6?.WaitForExit(1000);
// IPV6-Adresse hinzufügen.
psi.Arguments = $"http add sslcert ipport=[::]:{port} certhash={certificate.Thumbprint.ToLower()} appid={{{appId}}}";
Process procV6 = Process.Start(psi);
while (procV6 != null && !procV6.StandardOutput.EndOfStream)
{
str.Append(procV6.StandardOutput.ReadLine());
}
Log.Warn(str.ToString);
procV6?.WaitForExit();
*/
return true;
}
最佳答案
不幸的是,我认为普遍接受的方法是按你的方式调用 netsh 。您可以查看 Microsoft.Web.Administration.Binding ,但这取决于正在安装的 IIS。
IMO 执行 netsh http delete sslcert...
后执行 netsh http add sslcert...
是完全有效的。当绑定(bind)尚不存在时,删除
将会失败,但没关系。
关于C# 获取ssl服务器证书的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272790/