2013-02-21 32 views
1

從Web應用程序運行此代碼時,我看不到任何X509證書讀取證書存儲X509證書:不能在Web應用程序

var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); 
      store.Open(OpenFlags.ReadOnly); 

      string thumbprint = WebConfigurationManager.AppSettings["CertificateThumbprint"]; 

      if (string.IsNullOrWhiteSpace(thumbprint)) 
      { 
       throw new ArgumentException("Please specify the X509 certificate thumbprint in the web configuration file."); 
      } 

      Certificate = store.Certificates 
       .Find(X509FindType.FindByThumbprint, thumbprint, true) 
       .OfType<X509Certificate2>() 
       .FirstOrDefault(); 

      store.Close(); 

      if (Certificate == null) 
      { 
       throw new ArgumentException("The specified X509 certificate has not been installed on this server."); 
      } 

調試時,我可以看到store.Certificates是空的。然而,它在控制檯應用程序中運行得非常好..這很奇怪,因爲我在網上應用程序中使用上述代碼在線查看了示例。

如果代碼會拋出某種權限異常或Web應用程序中的某些內容來告訴我爲什麼我無法讀取它們,但它不會。那麼,我需要在某處設置一些權限嗎?

回答

1

我把證書中的TrustedPeople商店,而不是和它的作品罰款:

var store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);

0

爲了讓過去的權限問題,將證書導出到.pfx文件(密碼保護)。使用mmc:add管理單元 - >證書導出,然後將證書導出(並設置密碼)到一個方便的位置。然後

var certF = new X509Certificate2(
        @"D:\somedir\withaccess\exported.pfx", "password!"); 

爲什麼要從受信任的根證書頒發機構的StoreName.Root移動證書?

如果權限允許,則不在StoreName enums中的商店可以通過名稱來訪問,例如,對於「WebHosting」:

var store = new X509Store("WebHosting", StoreLocation.LocalMachine);