我如何在 IIS 中创建网站并使用 C# 从商店绑定证书?

How can i create a website in IIS and bind a certificate from the store using c#?

我尝试使用应用商店的证书在 IIS 中创建网站,但出现错误: 指定的登录会话不存在。它可能已经被终止。 (HRESULT 异常:0x80070520)

我正在使用以下代码创建网站:

证书从此代码中检索并传递给底部代码:

        X509Store store = new X509Store(StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
        X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificate Select", "Select a certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);
        var storeCertificate = scollection.Count > 0 ? scollection[0] : null;
        
        
        
        
        
        using (ServerManager iisManager = new ServerManager())
        {

            ServerManager serverManager = new ServerManager();                    
            X509Certificate2 certificate = null;
            if (storeCertificate != null)  
            {
                certificate = new X509Certificate2(storeCertificate);                        
                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
                store.Remove(certificate);                  
                store.Add(certificate);
                store.Close();
                Site website = iisManager.Sites.Add(name.ToString(), $"*:{port}:", location, certificate.GetCertHash());
                website.Applications[0].ApplicationPoolName = appPoolName;
                website.ServerAutoStart = true;
                iisManager.CommitChanges();
            }
        }

您可能需要将证书导出到文件中,然后将其加载到 X509Certificate2 对象中,然后添加到存储中,最后设置绑定。

将证书导出到文件:

File.WriteAllBytes(filePath, cert.Export(X509ContentType.Pkcs12, password))

然后通过执行以下操作将此证书文件导入商店:

var cert = new X509Certificate2(certFilePath, certPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

// My original AddCertToStore function
AddCertToStore(cert, StoreName.My, StoreLocation.LocalMachine, "Friendly Name"); 

最后像以前一样设置绑定。