我正在运行自托管的Web服务 . 通信是通过https,我使用自签名服务器认证 . 港口是多变的 . 因此,在每个应用程序启动时,我都在商店中查找证书并将其绑定到特定端口 . 我正在使用netsh和delete / add .
有没有办法找出“http add sslcert ipport = 0.0.0.0:”命令是否已经由应用程序启动执行?所以我不必删除并在每个app-start上添加它 . 我的想法是调用'http show sslcert ipport = 0.0.0.0:'并查看输出 . 但这不是那么好..所以有一个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;
}
1 回答
不幸的是,我认为通常可以这样做的方法是按照你的方式调用netsh . 您可以查看Microsoft.Web.Administration.Binding,但这取决于正在安装的IIS .
IMO完全有效的做
netsh http delete sslcert...
后跟netsh http add sslcert...
. 当绑定尚不存在时,delete
将失败,但这没关系 .