在.Net Core中使用HttpClient添加證書

最近公司要對接電信物聯網北向API接口,當調用Auth受權接口時,須要用到證書,此篇文章記錄下遇到的坑~服務器

有兩種調用接口的方式,下面是兩種方式的簡單示例app

一、使用HttpClienturl

public static void Post(string appId, string secret)
{
    var handler = new HttpClientHandler
    {
        ClientCertificateOptions = ClientCertificateOption.Manual,
        SslProtocols = SslProtocols.Tls12,
        ServerCertificateCustomValidationCallback = (x, y, z, m) => true,
    };

    var path = Path.Combine(AppContext.BaseDirectory, "cert\\iot3rd.p12");
    handler.ClientCertificates.Add(new X509Certificate2(path, "IoM@1234"));

    var client = new HttpClient(handler);

    var content = new StringContent($"appId={appId}&secret={secret}");
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    var httpResponseMessage = client.PostAsync("https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login", content).GetAwaiter().GetResult();
    var result = httpResponseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();

    Console.WriteLine(result);
}

二、使用HttpWebRequestcode

public static string Post(string appId, string secret)
{
    ServicePointManager.ServerCertificateValidationCallback = (x, y, z, m) => true;
    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

    HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create("https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login");
    var p12certfile = Path.Combine(AppContext.BaseDirectory, "cert\\iot3rd.p12");
    X509Certificate2 cerCaiShang = new X509Certificate2(p12certfile, "IoM@1234");
    httpRequest.ClientCertificates.Add(cerCaiShang);
    httpRequest.Method = "POST";
    httpRequest.ContentType = "application/x-www-form-urlencoded";

    Stream requestStem = httpRequest.GetRequestStream();
    StreamWriter sw = new StreamWriter(requestStem);
    sw.Write($"appId={appId}&secret={secret}");
    sw.Close();

    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

    Stream receiveStream = httpResponse.GetResponseStream();

    string result = string.Empty;
    using (StreamReader sr = new StreamReader(receiveStream))
    {
        return sr.ReadToEnd();
    }
}

須要注意一點,上面兩種方式都須要設置服務器證書驗證回調方法,不然回報下面的異常orm

The remote certificate is invalid according to the validation procedure.

並且兩種方式的設置方式不同,HttpClient是經過HttpClientHandler對象的ServerCertificateCustomValidationCallback屬性設置的,而HttpWebRequest方式是經過ServicePointManager.ServerCertificateValidationCallback來設置的對象

相關文章
相關標籤/搜索