在C#中很难将一个成功的Postman请求转换为一个成功的请求。显示我使用HttpClient的代码,但也尝试了PostSharp和HttpRequest。我使用的是一个有密码的本地pfx证书文件。
在 Postman :
- 将PFX证书添加到客户端证书
- “授权”选项卡包含用户名和密码(基本授权)
- 根据上述内容自动生成授权标题(“Basic〈encoded username/password〉”)
- 正文为“{}”
发送成功(200)。
使用HttpClient:
var host = @"https://thehost/service/verb?param1=blah¶m2=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;
}
这将返回Unauthorized(401)。响应文本包含“无效的用户名或密码”。
有没有想过这两个请求之间可能不匹配的地方?
1条答案
按热度按时间4c8rllxm1#
你试过使用Postman代码片段自动生成代码吗?它使用RESTSharp API客户端库for C#。
点击〈/〉图标并选择“C# - RestSharp”,它应该会给予你代码。
https://learning.postman.com/docs/sending-requests/generate-code-snippets/