[英]Adding .pfx certificate to HttpWebRequest fails from Web application
I have created a Asp.net web application-C#, where I need to send a HttpWebRequest with a .pfx certificate. 我创建了一个Asp.net Web应用程序-C#,我需要在其中发送带有.pfx证书的HttpWebRequest。
I have installed the certificate to the personal certificates folder(added rights for user NETWORK SERVICE) and able to see it in the X509Certificate2Collection and no issues while adding the certificate to the HttpWebRequest. 我已经将证书安装到个人证书文件夹(为用户NETWORK SERVICE添加了权限),并且能够在X509Certificate2Collection中看到它,并且在将证书添加到HttpWebRequest时没有问题。
But it throws cannot connect to server error while fetching the response (HttpWebResponse)req.GetResponse() 但是,在获取响应(HttpWebResponse)req.GetResponse()时,它无法连接到服务器错误
I am facing this issue only from web application, the same code works fine(got the correct response) when i tried using a C# console application. 我仅从Web应用程序面临此问题,当我尝试使用C#控制台应用程序时,相同的代码可以正常工作(获得正确的响应)。
X509Store oLocalMachineStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
X509Certificate2Collection oCertColl;
X509Certificate oCert = new X509Certificate();
oLocalMachineStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
oCertColl = oLocalMachineStore.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByIssuerName, "mycertificate issuer", false);
oLocalMachineStore.Close();
foreach (X509Certificate oCertFromStore in oCertColl)
{
if (oCertFromStore.Issuer.Contains("mycertificate issuer"))
{
oCert = oCertFromStore;
oCert.Import(@"certlocation\mycertificate.pfx", "pwd", X509KeyStorageFlags.MachineKeySet);
break;
}
}
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("destination URL");
req.ClientCertificates.Add(oCert);
req.UserAgent = "LOL API Client";
req.Accept = "application/json";
req.Method = WebRequestMethods.Http.Get;
string result = null;
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
The issue got resolved after adding proxy to the http request. 将代理添加到http请求后,该问题已解决。
req.Proxy = New Net.WebProxy("ProxyURL", False);
But still i have no idea, how it worked when i tried with the same code from a console application with out adding proxy. 但是我仍然不知道,当我尝试从控制台应用程序使用相同代码而不添加代理时,它是如何工作的。
If anyone has any idea on this please share. 如果有人对此有任何想法,请分享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.