I would like to use a certificate in my gRPC client. I am trying doing this:
public ServiceClientGrpc(string paramDireccion, int paramPuerto, string paramCertificado, string paramKey)
{
var cert = X509Certificate2.CreateFromPem(paramCertificado, paramKey);
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);
HttpClient httpClient = new(handler);
var channel = GrpcChannel.ForAddress(paramDireccion + ":" + paramPuerto, new GrpcChannelOptions
{
HttpClient = httpClient
});
_client = new Greeter.GreeterClient(channel);
}
My problem is in this two lines:
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);
handler is not null, but the collecion ClientCertificates is null, so I get an exception when I try to add the certificate.
According to the Microsfot documentantion, it is the way to do it.
public Ticketer.TicketerClient CreateClientWithCert(
string baseAddress,
X509Certificate2 certificate)
{
// Add client cert to the handler
**var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);**
// Create the gRPC channel
var channel = GrpcChannel.ForAddress(baseAddress, new GrpcChannelOptions
{
HttpHandler = handler
});
return new Ticketer.TicketerClient(channel);
}
How could I add the certificates to my handler?
Thanks.
EDIT: I create a WPF project which target is .NET 6.0 too with one button. The code.behind is this:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); }
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Net.Http.HttpClientHandler miHandler = new System.Net.Http.HttpClientHandler();
}
}
When I set a breakpoint at the end of the method, I can see that ClientCertificates is not null.
EDIT 2: So the problem is in my MAUI project, when I debug in my phone, the collection is null, but if I use the same library in my WPF project it works.
So it seems that there is some problem when I use the library in my MAUI project.