C# · 12月 27, 2021

c# – IIS 7.x,添加启用HTTPS的站点:SiteCollection.Add(string,string,string,byte [])overload

我需要以编程方式添加一个IIS 7.x站点,当我们默认使用HTTPS / SSL绑定来创建这个应用程序时,我将陷入困境,usig SiteCollection.Add(string,string,byte[]) overload.

给予https:*:80:test.localhost https:*:443:test.localhost作为bindingInformation抛出一个带有此消息的ArgumentException:指定的HTTPS绑定无效.

这个绑定信息有什么问题?

谢谢.

编辑:我正在使用Microsoft.Web.Administration程序集.

解决方法 这是我做了什么来创建https网站,它的工作.当然,我在这里跳过一些代码. using Microsoft.Web.Administration…using(var manager = new ServerManager()){ // variables are set in advance… var site = manager.Sites.Add(siteName,siteFolder,siteConfig.Port); var store = new X509Store(StoreName.AuthRoot,StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); // certHash is my certificate’s hash,byte[] var binding = site.Bindings.Add(“*:443:”,certHash,store.Name); binding.Protocol = “https”; store.Close(); site.ApplicationDefaults.EnabledProtocols = “http,https”; manager.CommitChanges();}

UPD:证书是通过以下方式从pfx文件创建的:

// get certificate from the filestring pfx = Directory.GetFiles(folder,”*.pfx”,SearchOption.AllDirectories).FirstOrDefault();var store = new X509Store(StoreName.Root,StoreLocation.LocalMachine);store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);var certificate = new X509Certificate2(pfx,certPassword,X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);store.Add(certificate);store.Close();certHash = certificate.GetCertHash();