获取Azure证书时发生异常

本文关键字:异常 Azure 证书 获取 | 更新日期: 2023-09-27 18:01:02

我正在开发一个windows服务,该服务将调用Microsoft Azure Management Libraries来管理云服务。但在这样做的同时,我的程序不会返回用于管理云活动的凭据。当我在控制台应用程序中测试相同的代码时,它每次都运行良好,但当我将代码与Windows服务集成时,用于获取凭据的函数会给出异常Index was out of range. Must be non-negative and less than the size of the >>collection. Parameter name: index。我不明白为什么这个代码在返回证书时表现不正确。但由于类X509Certificate2Collection无法找到证书并返回集合,因此发生了异常。因此,我的代码失败了。我的问题是:

  1. 有人能告诉我解决上述错误的可能解决方案是什么吗。

  2. 当我在Windows服务中集成相同的代码时,为什么我的代码表现不同?

供参考http://www.bradygaster.com/post/getting-started-with-the-windows-azure-management-libraries

//代码

internal class CertificateAuthenticationHelper
{
    internal static SubscriptionCloudCredentials GetCredentials(
        string subscrtionId,
        string thumbprint)
    {
        return new CertificateCloudCredentials(subscrtionId, GetCertificate(thumbprint));
    }
    private static X509Certificate2 GetCertificate(string thumbprint)
    {
        X509Store certStore = null;
        X509Certificate2Collection certCollection = null;
        X509Certificate2 certificate = null;
        // Open the certificate store for the current user.
        certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        //certStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
        certStore.Open(OpenFlags.ReadOnly);
        // Find the certificate with the specified thumbprint.
        certCollection = certStore.Certificates.Find(
                             X509FindType.FindByThumbprint,
                             thumbprint,
                             false);
        certStore.Close();
        // A matching certificate was found.
// Here I am getting exception as my function is unable to find any matching certificate. 
//I checked my certCollection.Count which is 0 in Windows Service. But when I am debugging the same code in Console Application its returning 1. 
            certificate = certCollection[0];
            return certificate;
        }
    }

获取Azure证书时发生异常

请将管理证书放入LocalMachine证书存储区,而不是CurrentUser存储区,并相应地更改代码以从LocalMachine存储区读取。

从错误消息中可以看出,您的Windows服务在CurrentUser存储中找不到该证书。很可能是因为Windows服务在不同的用户上下文下运行。