我开发了一个自托管api。
api流量需要通过SSL运行。
使用netsh命令的组合我已成功添加证书,然后将路由绑定到我的服务。快乐的日子。
但是,我必须编写一个安装程序来以编程方式执行此操作。
问题是,当我使用我的c#代码添加证书时,我可以看到证书MMC,但是当我尝试绑定到它时,我收到错误:
SSL Certificate add failed, Error: 1312
A specified log-on session does not exist. It may already have been terminated.
正如我所说,当我手动执行这些步骤时,我没有遇到问题......
然后我可以在个人>下的MMC中看到它。证书
它允许我在命令提示符下使用netsh添加路由 - Happy Days。
当我尝试使用以下代码以编程方式执行此操作时:
public static bool ConfigureSSLCertificate(string file, string password, string method)
{
try
{
X509Certificate2 cert = new X509Certificate2(file, password);
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
if (!store.Certificates.Contains(cert))
{
if (method == "add")
{
store.Add(cert);
}
}
if (method == "remove")
{
store.Remove(cert);
}
return true;
}
catch { return false; }
}
证书出现在我的MMC中完全相同的位置,但当我尝试使用与之前完全相同的netsh命令添加路由时,我得到上述错误:
netsh>http add sslcert ipport=0.0.0.0:8088 certhash=fb93ce2c4d8bd88c82e63e3372a050ba84f15e94 appid={bb14356a-a14f-4589-82ce-b80d38b8741e}
出于某种原因,当我使用MMC手动添加证书时,当我运行我的代码时,有些不同。正在阻止添加路线的东西。
答案 0 :(得分:1)
解决方案实际上很简单 - 我也一直在努力解决这个问题,现在已经找到了解决方案。如何手动添加证书与以编程方式添加的证书不同?嗯,简短的回答是将证书加载行更改为:
X509Certificate2 cert = new X509Certificate2(file, password, X509KeyStorageFlags.MachineKeySet);
关键是最后一个参数,它告诉证书保存存储在机器位置的私钥,而不是用户位置。然后netsh
命令可以找到私钥,并且可以工作。
解决方案在Paul Stovell的解释性文本中找到,并且有些人在将证书加载到商店时如何设置该标志。
现在,为什么我不能以编程方式执行netsh功能是另一回事......
答案 1 :(得分:0)
我想我已经修好了。
我尝试安装的.pfx存在问题。我不知道为什么。修复它的原因是从我的个人商店导出一个工作证书,所有选项都设置为true,然后按以下方式运行:
public static bool ServiceInstall(string serviceName, string serviceDescription, string executablePath)
{
try
{
ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();
ProcesServiceInstaller.Account = ServiceAccount.LocalSystem;
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
InstallContext Context = new System.Configuration.Install.InstallContext();
String path = String.Format("/assemblypath={0}", executablePath);
String[] cmdline = { path };
Context = new System.Configuration.Install.InstallContext("", cmdline);
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.DisplayName = serviceName;
ServiceInstallerObj.Description = serviceDescription;
ServiceInstallerObj.ServiceName = serviceName;
ServiceInstallerObj.StartType = ServiceStartMode.Automatic;
ServiceInstallerObj.Parent = ProcesServiceInstaller;
System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
ServiceInstallerObj.Install(state);
return true;
}
catch
{
return false;
}
}
然后使用该pfx文件
我不知道为什么旧的pfx从命令行工作但是没有从代码中工作。
HTH