将工作邮递员请求转换为 C# (HttpClient)

Phi*_*ler 1 c# ssl-certificate dotnet-httpclient postman

很难将成功的 Postman 请求转换为 C# 中的成功请求。使用 HttpClient 显示我的代码,但也尝试使用 PostSharp 和 HttpRequest。我正在使用带有密码的本地 pfx 证书文件。

在邮递员中:

  • 将 PFX 证书添加到客户端证书
  • 授权选项卡有用户名和密码(基本身份验证)
  • 根据上述自动生成授权标头(“Basic <encoded username/password>”)
  • 主体是“{}”

发送成功(200)。

使用 HttpClient:

var host = @"https://thehost/service/verb?param1=blah&param2=1111111";
const string certName = @"C:\Key.pfx";
const string userName = "userName";
const string certPassword = "password1";
const string authPassword = "password2";

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;

// tried many combinations here
handler.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 |
                       SslProtocols.Tls12 | SslProtocols.Tls13;

var cert = new X509Certificate2(certName, certPassword);
handler.ClientCertificates.Add(cert);
//not sure if this is needed
handler.ServerCertificateCustomValidationCallback += (message, certificate2, arg3, arg4) => true;
            
var client = new HttpClient(handler);
//not sure if these are needed
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
// added this to both the request and the client. 
// Also tried "*/*" for both
client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
            
var request = new HttpRequestMessage();
request.RequestUri = new Uri(host);
request.Headers.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent("{}", Encoding.UTF8, 
                                     "application/json");
request.Method = HttpMethod.Post;

//basic auth header
var authenticationString = $"{userName}:{authPassword}";
var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.UTF8.GetBytes(authenticationString));
var authHeader = new AuthenticationHeaderValue("Basic", 
                     base64EncodedAuthenticationString);
request.Headers.Authorization = authHeader;

try
{
   var httpResponseMessage = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
}catch (Exception e){
   Console.WriteLine(e);
   throw;
}
Run Code Online (Sandbox Code Playgroud)

这将返回未经授权 (401)。响应文本包含“无效的用户名或密码”。

对于这两个请求之间可能不匹配的地方有什么想法吗?

w4d*_*325 5

您是否尝试过使用 Postman 代码片段自动生成代码?它使用 C# 的 RESTSharp REST API 客户端库。

单击 </> 图标并选择“C# - RestSharp”,它应该会为您提供代码。

在此输入图像描述

https://learning.postman.com/docs/sending-requests/generate-code-snippets/

  • 我很欣赏它有 RestSharp,但问题是我正在寻找 HttpClient 代码。 (5认同)