获取 Azure 证书时出现异常

Exception occurred while fetching Azure certificate

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

  1. Can anyone tell me what is the possible solution to solve this above discussed error.

  2. Why my code is behaving differently when I integrated the same code in Windows Service?

供参考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;
        }
    }

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

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