我遇到了一个问题,即在调用 Azure APIM 时需要包含客户端证书。使用 Postman 或用 .NET Framework 4.8 编写的 C# 代码时,一切正常。但是,当尝试在 .NET 8.0 中执行相同的代码时,它无法工作。
有人知道为什么我无法使用客户端证书成功发送请求吗?
以下是参考代码片段。
var cert = new X509Certificate2("D:\\MyFolder\\MyCertificate.pfx", "certificatepassword");
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);
handler.SslProtocols = SslProtocols.Tls12;
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Post, "https://APIMURL.com");
request.Headers.Add("Ocp-Apim-Subscription-Key", "key");
var content = new StringContent("{\"action\":\"myaction\"}", null, "text/plain");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
你的代码在 .NET8 中确实对我有用。
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
var cert = new X509Certificate2("C:\\Users\\Downloads\\afreen12-MyCertificate-20240426.pfx", {certificatePassword});
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);
handler.SslProtocols = SslProtocols.Tls12;
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Post, "https://{apim_Name}.azure-api.net/echo/resource");
request.Headers.Add("Ocp-Apim-Subscription-Key", "02ca*********7753");
var content = new StringContent("{\"vehicleType\": \"train\",\"maxSpeed\": 125,\"avgSpeed\": 90,\"speedUnit\": \"mph\"}", null, "text/plain");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
.csproj-
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
我能够得到预期的输出。
请检查您是否使用了正确的凭据,例如证书密码、Ocp-Apim-Subscription-Key。