Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

PHP/Curl-SSL operations alternative in C#

I have this piece of code written in PHP, which adds, as i presume, some information about an SSL-certificate to a HTTP-request(It's just a simple http-request, isn't it?). It's added either to body-request or header, that i don't know for sure.

//some code before that
curl_setopt($curl,CURLOPT_SSLCERT,'cert.crt');
curl_setopt($curl,CURLOPT_SSLKEY,'cert.key');
//some code after

//the request itself
$json_response = curl_exec($curl);

The problem is - i don't know how to make this stuff in C#. It'd be easy if i had any knowledge how it's done in curl, like what it exactly does under it's cover.

My current request.

      //
            var request = CreateHttpRequest(url, method);
            var json = param?.ToJson();


            if (json != null)
            {
                var postData = Encoding.UTF8.GetBytes(json);
                request.ContentLength = postData.Length;
                using (var stream = request.GetRequestStream())
                    stream.Write(postData, 0, postData.Length);
            }

            using (var webResponse = request.GetResponse())
            using (var streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
             {
                    var result = streamReader.ReadToEnd();
                    return result.ParseJson(type);
             }

    //
    private HttpWebRequest CreateHttpRequest(string url, HttpMethod method)
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "application/json";
        request.Accept = "application/json, application/javascript, text/*";
        request.Headers.Add("Accept-Encoding", "gzip,deflate");
        request.Method = method.ToString().ToUpper();
        return request;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to use client certificate (loaded from .crt and .key files) in your HTTP-request, add following lines in CreateHttpRequest method before return:

string certificateText = File.ReadAllText("cert.crt");
string privateKeyText = File.ReadAllText("cert.key");
ICertificateProvider provider =
    new CertificateFromFileProvider(certificateText, privateKeyText);

request.ClientCertificates.Add(provider.Certificate);

Taken from this answer. To have CertificateFromFileProvider install OpenSSL.X509Certificate2.Provider Nuget package.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...