使用证书

时间:2017-02-14 16:08:01

标签: c# .net certificate

我正在尝试向服务器发送POST请求。我将证书附加到请求,但服务器返回400 Bad Request。有关如何使其工作的任何想法? 该代码既不在控制台应用程序中也不在IIS上托管的Web Api应用程序中工作。 以下对服务器的curl请求有效 curl -vvvv -H" Content-Type:application / json" -X POST -d'数据' --cert ./certname.cer --user用户:" Pass" https://domain/api/inventory

        X509Store xstore = new X509Store(StoreLocation.CurrentUser);
        xstore.Open(OpenFlags.ReadOnly);
        var cert = new X509Certificate2(path);

        var URL = "https://domain/api/inventory";
        var username = "User";
        var password = "Pass";
        var DATA = "data";

        var encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = DATA.Length;
        request.Accept = "*/*";
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.ClientCertificates.Add(cert);

        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            var requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
            requestWriter.Write(DATA);
            requestWriter.Close();

            var webResponse = request.GetResponse();
            var webStream = webResponse.GetResponseStream();
            var responseReader = new StreamReader(webStream);
            var response = responseReader.ReadToEnd();
            Console.WriteLine(response);
            responseReader.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("-----------------");
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            Console.WriteLine("inner stacktrace");

            if (e.InnerException != null)
            {
                Console.WriteLine(e.InnerException.ToString());
            }
        }

0 个答案:

没有答案