我已经花了一整天的时间在这件事上,除了向我的同事请教之外,我看不到任何出路。
我们有一个接受X509证书的web api,但是下面的代码总是在本地主机和开发服务器上都给我空值。
下面是我获取证书的代码:
var certificate = actionContext.Request.GetClientCertificate();我已经创建了一个ActionFilterAttribute,在它的OnActionExecuting中,我正在尝试获得上面提到的客户端证书。
在此之前,我按照this link上的说明使用following创建了证书
我使用的命令是这样的:
New-SelfSignedCertificate -DnsName "localhost", "atp api" -CertStoreLocation "cert:\LocalMachine\My"证书已创建,并且我确保它位于受信任的证书中。然后,在我的示例客户端应用程序中,我使用以下代码将证书发送到我的Web API:
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
var certCollection = store.Certificates.Find(X509FindType.FindByIssuerName, "localhost", false);
var cert = certCollection[0];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://localhost:44308/dk");
request.ClientCertificates.Add(cert);
request.Method = "POST";
string postData = "<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'>sample string 1</string>";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//request.ContentType = "application/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
store.Close();但是当这段代码在我的Web API中执行时,证书是空的。我想可能是因为localhost,我在开发服务器上部署了web api,证书仍然是空的。
我还尝试从指定的windows位置而不是从商店获取证书,结果是相同的。
我搜索了一遍又一遍,但都没有帮到我。
发布于 2017-04-21 22:49:35
设置request的ServerCertificateValidationCallback属性
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;ServerCertificateValidationCallback是一种验证服务器证书的方法。因此,request将忽略证书错误。如果您使用的是低于4.5版本的.NET框架,您可以为ServicePointManager.ServerCertificateValidationCallback设置相同的回调。如果需要,您可以检查证书的自定义验证。
https://stackoverflow.com/questions/43246583
复制相似问题