HttpClient,HTTP / 2和客户端证书.pfx,.p12

时间:2017-06-13 11:41:14

标签: c# asp.net .net-core asp.net-core-1.0 asp.net-core-webapi

如何在.Net Core> = 1.0

中重写这段c#代码

我已经读过HttpClient不支持 https://github.com/dotnet/corefx/issues/4479

.Net Framework 4.5版本

HttpWebRequest request = WebRequest.Create(this.endPoint) as HttpWebRequest;
request.ContentType = "application/json;charset=UTF8";
X509Certificate2 cert = new X509Certificate2(this.certFileName);
request.ClientCertificates.Add(cert);
request.Accept = "application/json";
request.Method = WebRequestMethods.Http.Get;

string result = null;
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
    StreamReader reader = new StreamReader(resp.GetResponseStream());
    result = reader.ReadToEnd();
}

Console.WriteLine(result);

解决方案: - .Net Core Version

最后设法让它工作,虽然必须将证书从.p12更改为.pfx(私钥+ SSL证书)。它不适用于.p12。

    private FormUrlEncodedContent GetLoginBodyAsContent(string username, string password)
    {
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("username", username));
        postData.Add(new KeyValuePair<string, string>("password", password));
        return new FormUrlEncodedContent(postData);
    }

    private async Task<LoginResponse> Login(string username, string password, string certFilename)
    {
        var clientHandler = GetClientHandler();

        var handler = AddCert(clientHandler, certFilename);
        var client = InitHttpClientInstance(handler, this.AppKey);

        var content = GetLoginBodyAsContent(username, password);

        var result = await client.PostAsync("/api/certlogin", content);
        result.EnsureSuccessStatusCode();
        var jsonSerialiser = new DataContractJsonSerializer(typeof(LoginResponse));
        var stream = new MemoryStream(await result.Content.ReadAsByteArrayAsync());
        var response = (LoginResponse)jsonSerialiser.ReadObject(stream);
        return response;
    }
    private HttpClientHandler AddCert(HttpClientHandler clientHandler, string certFilename)
    {
        var certPfx = new X509Certificate2(certFilename);
        clientHandler.SslProtocols = SslProtocols.Tls12;
        clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
        clientHandler.ClientCertificates.Add(certPfx);

        clientHandler.ServerCertificateCustomValidationCallback += 
            (HttpRequestMessage req, X509Certificate2 cert2, X509Chain chain, SslPolicyErrors err) => { return true; };

        return clientHandler;
    }
    private HttpClient InitHttpClientInstance(HttpMessageHandler clientHandler, string appKey, string baseUrl = DefaultAuthServiceUrl)
    {
        var client = new HttpClient(clientHandler);
        client.BaseAddress = new Uri(baseUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("X-Application", appKey);
        client.DefaultRequestHeaders.ExpectContinue = true;
        client.DefaultRequestHeaders.Add("Connection", "Close");

        return client;
    }
    private HttpClientHandler GetClientHandler()
    {
        var clientHandler = new HttpClientHandler();
        return clientHandler;
    } 

似乎.net核心意味着让生活变得困难..太多的样板,容易弄错。

0 个答案:

没有答案