需要检查附加在HTTP请求中的证书详细信息。

huangapple go评论63阅读模式
英文:

Need to inspect the Certificate Details attached with HTTP request

问题

我已经附上了一个证书,使用HTTP客户端,并希望在发送请求到服务器之前或之后记录证书详情。

我尝试了下面的代码,但它不起作用

var cert = ServicePointManager.FindServicePoint(new Uri(path)).Certificate;

可以有人帮我提供C#代码片段以获取证书详情,以便我可以记录它。

英文:

I have attached a certificate with HTTP Client and wants to log the cert details just before or after sending the request to the server.

I tried below code but it is not working

var cert = ServicePointManager.FindServicePoint(new Uri(path)).Certificate;

Can someone please help me with C# code snippet to get the cert details so that I can log it.

答案1

得分: 1

你可以创建一个自定义的 HttpClientHandler,并在 SendAsync 方法内添加日志记录逻辑,像这样:

public class MyMessageHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        foreach (var cert in ClientCertificates)
        {
            Console.WriteLine(cert.ToString(true));
        }

        var response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}

var handler = new MyMessageHandler();
handler.ClientCertificates.Add(GetCertificateFromStore("CN=localhost"));
var client = new HttpClient(handler);
英文:

You can create a custom HttpClientHandler and add logging logic inside the SendAsync method like this:

public class MyMessageHandler : HttpClientHandler
{
    protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        foreach (var cert in ClientCertificates)
        {
            Console.WriteLine(cert.ToString(true));
        }

        var response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}


var handler = new MyMessageHandler();
handler.ClientCertificates.Add(GetCertificateFromStore(&quot;CN=localhost&quot;));
var client = new HttpClient(handler);

huangapple
  • 本文由 发表于 2023年3月7日 06:26:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656405.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定