从我的WebSite应用程序中引用.pfx文件

时间:2015-10-09 08:50:50

标签: c# asp.net web-services

我正在开发一个使用Web服务的WebSite但我在代码中引用客户端证书文件时遇到了问题。

我已将.pfx文件添加到解决方案中,如下所示。

pfx

这是我尝试构建文件链接的方法,并将客户端证书添加到我的服务中:

var certName = "665300-ws-hg-test.pfx";
var newCertPath = Path.Combine(Environment.CurrentDirectory, @"WebSite2\", certName);

DocArchiveV201101 service = new DocArchiveV201101();
service.ClientCertificates.Add(
    new System.Security.Cryptography.X509Certificates.X509Certificate(
        newCertPath, certPass));

打印newCertPath时:

C:\Program Files (x86)\IIS Express\WebSite2\665300-ws-hg-test.pfx

最后一行代码会引发以下错误:

System.Security.Cryptography.CryptographicException was unhandled by user code
  HResult=-2147024893
  Message=the system cannot find the file specified.
  Source=mscorlib
  StackTrace:
       vid System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
       vid System.Security.Cryptography.X509Certificates.X509Utils._QueryCertFileType(String fileName)
       vid System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)
       vid System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password)
       vid ASP._Page_index_cshtml.Execute() i c:\Users\marcus.jacobsson\Documents\Visual Studio 2015\WebSites\WebSite2\index.cshtml:rad 47
       vid System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       vid System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors)
       vid System.Web.WebPages.WebPage.ExecutePageHierarchy()
       vid System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
       vid System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase httpContext)
  InnerException: 

所以我的问题是;如何构建适当的链接以引用项目中的665300-ws-hg-test.pfx文件?

1 个答案:

答案 0 :(得分:1)

您需要使用HostingEnvironment.MapPath方法。此外,如果证书位于网站根目录中,则无需在证书名称前加上项目文件夹名称:

var newCertPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~\" + certName);