首页 > 解决方案 > 从asp.net核心资源中读取嵌入文件

问题描述

将我的网站发布到 iis 后,出现以下错误:

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException:系统找不到指定的文件

我从嵌入式文件中读取 X509Certificate2 的代码是:

X509Certificate2 certificate = null;
using (var certStream = typeof(T).Assembly.GetManifestResourceStream(resourceName))
{
    using (var memory = new MemoryStream((int)certStream.Length))
    {
        certStream.CopyTo(memory);
        certificate = new X509Certificate2(memory.ToArray(), password);
    }
}

这个错误只发生在windows server IIS中,但是如果直接运行Kestrel,在IIS Express中没有问题。

流上的断点

它将文件作为非托管内存读取。

标签: c#asp.net-core-mvc

解决方案


我遇到了同样的问题,添加 X509KeyStorageFlags.MachineKeySet 就可以了。

certificate = new X509Certificate2(memory.ToArray(), password, X509KeyStorageFlags.MachineKeySet);

在这里找到解决方案:

https://github.com/dotnet/corefx/issues/27358#issuecomment-385433985

http://web.archive.org/web/20151101033040/http://blog.tylerdoerksen.com:80/2013/08/23/pfx-certificate-files-and-windows-azure-websites/

https://stackoverflow.com/a/48234395/3080858


推荐阅读