.NET X509Certificate2 authentication

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Encoding.RegisterProvider(new Utf8EncodingProvider());
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            X509Certificate2 certificate = new X509Certificate2(Server.MapPath("tokla.pfx"), "12345678", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            HttpClientHandler handler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
                {
                    return true;
                }
            };

            handler.ClientCertificates.Add(certificate);
            HttpClient httpClient = new HttpClient(handler);

            HttpContent context = new StringContent(string.Empty, Encoding.UTF8, "application/xml");
            var response = httpClient.PostAsync("https://domain_url:5443/Exec", context).Result;
            var content = response.Content.ReadAsStringAsync().Result;

            Label2.Text = content;
        }
    }

    public class Utf8EncodingProvider : EncodingProvider
    {
        public override Encoding GetEncoding(string name) => !(name == "UTF8") ? (Encoding)null : Encoding.UTF8;

        public override Encoding GetEncoding(int codepage) => (Encoding)null;
    }
创建时间:8/25/2022 5:48:45 PM 修改时间:8/27/2022 9:21:57 PM