我正在开发一个Windows服务,它将调用Microsoft Azure Management Libraries
来管理云服务。但在这样做的同时,我的程序没有返回用于管理云活动的凭据。当我在Console Application中测试相同的代码时,它每次都运行良好,但是当我将代码与Windows Services集成时,用于获取凭据的函数给出异常Index was out of range. Must be non-negative and less than the size of the >>collection. Parameter name: index
。
我不知道为什么这个代码在返回证书时行为不正确。但是由于类X509Certificate2Collection
无法找到证书并返回集合而发生异常。因此我的代码失败了。我的问题是:
任何人都可以告诉我解决上述错误的可能解决方案是什么。
- 醇>
为什么在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;
}
}
答案 0 :(得分:1)
请将管理证书放在a b
1 22
2 23
证书商店而不是LocalMachine
商店,并相应更改代码,以便从CurrentUser
商店阅读。
从错误消息中可以看出,您的Windows服务无法在LocalMachine
商店中找到该证书。很可能是因为Windows服务在不同的用户环境下运行。