MVC Webapi无法检索证书

时间:2019-04-30 07:47:21

标签: c# asp.net-web-api2 ssl-certificate x509certificate

我在本地主机上有一个Webapi应用程序,在开发计算机上也有一个控制台应用程序。

我已经在我的Visual Studio中启用了“ Required SSL”属性,并在webapi上添加了RequiredHTTPS。但是,当我将.Cer从控制台应用程序发送到webapi时,webapi不会检索任何证书。 非常感谢有人可以帮助我。 我正在使用iis Express本地主机证书 这是我的代码。 WebAPI

 HttpResponseMessage response = new HttpResponseMessage();
        X509Certificate2 clientCertInRequest = RequestContext.ClientCertificate; //null here
        X509Certificate2 clientCertInRequest2 = Request.GetClientCertificate();//null here as well
        if (clientCertInRequest != null)
        {

       //function
            return Task.FromResult(response);
        }

        }
        response = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");
        return Task.FromResult(response);
    }

控制台应用程序 调用webapi的功能

  X509Certificate2 clientCert = GetClientCertificate();
                WebRequestHandler requestHandler = new WebRequestHandler();
                requestHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
                requestHandler.ClientCertificates.Add(clientCert);
                HttpClient client = new HttpClient(requestHandler);
                HttpResponseMessage response = await client.PostAsync("api/apicontroller/myAPIMethod", stringContent);

在控制台中获取证书的功能

 X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        try
        {
            userCaStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
            X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySerialNumber, "myserialnumber", true);
            X509Certificate2 clientCertificate = null;
            if (findResult.Count == 1)
            {
                clientCertificate = findResult[0];//i do get one cert from this line
            }
            else
            {
                throw new Exception("Unable to locate the correct client certificate.");
            }
            return clientCertificate;
        }
        catch
        {
            throw;
        }
        finally
        {
            userCaStore.Close();
        }
    }
}

0 个答案:

没有答案