问题描述:

I'm trying to send POST request to a server. I'm attaching certificate to request, but the server return 400 Bad Request. Any ideas on how to make it work?

The code does not work neither in Console application nor in Web Api app hosted on IIS.

The following curl request to the server works

curl -vvvv -H "Content-Type: application/json" -X POST -d 'data' --cert ./certname.cer --user 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());

}

}

相关阅读:
Top