加载 X509Certificate2 导致 ASP.NET MVC 网站崩溃

Loading X509Certificate2 crashing the ASP.NET MVC website

只是我有 X509Certificate2 证书,我想将其加载到 ASP.NET MVC 应用程序中。

这里就是代码

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        string path = HostingEnvironment.MapPath("~/Certificates.p12");
        // the path is correct, I logged it to a file and it was correct

        byte [] certBytes = File.ReadAllBytes(path);
        X509Certificate2 cert = new X509Certificate2(certBytes, "some password");
    }
}

即使这样也行不通

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        string path = HostingEnvironment.MapPath("~/Certificates.p12");
        // the path is correct, I logged it to a file and it was correct

        X509Certificate2 cert = new X509Certificate2(path, "some password");
    }
}

在前两种情况下,代码在我的本地机器上运行,但是当将这段代码移动到我们的服务器时,语句

X509Certificate2 cert = new X509Certificate2(/*whatever bytes or path*/, "some password");

正在中断,实际上这个语句让我的 IIS 的应用程序池停止,并且当我尝试访问该网站时出现 Http 503 服务不可用错误。

当我去掉前面的语句后,就没有503错误了,网站可以访问了。

我试图将此语句移动到另一个class(不放在网站的启动中)但结果是一样的。

EDIT 由于某些非常奇怪的原因,我无法记录发生的异常。 所以我不知道这个

的确切问题是什么

EDIT 我刚刚创建了一个小型控制台应用程序,我试图从中读取相同的证书文件,它在我的本地机器和服务器上都运行良好,所以我怀疑问题不是来自证书文件,也不是来自服务器,而是 ASP.NET MVC 项目与证书文件的组合产生了这个问题

编辑
这是服务器的事件日志

Application pool 'SmaresDev' is being automatically disabled due to a series of failures in the process(es) serving that application pool.


A process serving application pool 'SmaresDev' suffered a fatal communication error with the Windows Process Activation Service. The process id was '8520'. The data field contains the error number.


A fatal alert was generated and sent to the remote endpoint. This may result in termination of the connection. the TLS protocol defined fatal error code is 10. The windows SChannel error state is 1203.


任何想法。

我遇到了类似崩溃的情况,但没有捕获到任何异常。我在事件查看器中遇到了类似的问题,并且 运行 在控制台应用程序工作正常的情况下也遇到了同样的问题。我修复如下

X509Certificate2 Cert = new X509Certificate2(path, "some password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

我不确定它为什么有效,但它对我有用,希望对你也有用。