Adding https binding from ASP.NET MVC application hosted

0

I have an Application hosted in IIS website TestWebsite and i am using Microsoft.Web.Administration for IIS Automation.

I have to do following operations with bindings of the SAME website TestWebsite from TestWebsite

  1. Add HTTPS binding with SSL certificate to the website "TestWebsite" from same application (code to add binding will be in same "TestWebsite")
  2. Remove the Binding.

I have done the following code and weird thing is that on localhost it is adding the https binding but even before manager.commitchange(). This line throw exception on local host, so i removed this line but on Windows Server its not adding the binding even after successfully running the code. (without commitchanges(), i hv no idea how its working on localhost without it)

I am using IIS 10 on localhost and IIS 8.5 on staging and IIS 8.0 On Production.

using (ServerManager iisManager = new ServerManager())
{
    var website = iisManager.Sites.Where(x => x.Name == "TestWebsite").FirstOrDefault();
    if (website != null)
    {
        var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
        var pfxPath = Server.MapPath(model.PfxPath);
        var certificate = new X509Certificate2(pfxPath, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
        store.Add(certificate);
        store.Close();
        var certHash = certificate.GetCertHash();

        string bindingInformation = string.Format("{0}:{1}:{2}", "*", "443", model.UserCustom);
        var binding = website.Bindings.Add(bindingInformation, certHash, store.Name);
        binding.Protocol = "https";
        store.Close();

        website.ApplicationDefaults.EnabledProtocols = "http,https";
        iisManager.CommitChanges();
    }
}

I receive following error on iisManager.CommitChanges() line

A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)

Is there some permission related error? What i am doing wrong in it?

Your help will be appreciated

Thank you :) Danial Malik

c#
asp.net-mvc
iis
iis-8
iis-10
asked on Stack Overflow Sep 24, 2019 by Danyal Malik

1 Answer

0

IIS would return 0x80070520 error when Adminsitrators group don't have permission to access C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys. Please try to grant full control permission for your administrators group.

https://www.cnblogs.com/ziye/p/9208353.html

https://blogs.msdn.microsoft.com/asiatech/2010/08/12/got-error-0x80070520-when-binding-certificate-to-web-site-on-iis-7/

answered on Stack Overflow Sep 25, 2019 by Jokies Ding

User contributions licensed under CC BY-SA 3.0