简体   繁体   English

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

[英]Convert Working Postman Request to C# (HttpClient)

Having a hard time converting a successful Postman request to a successful request in C#.很难将成功的 Postman 请求转换为 C# 中的成功请求。 Showing my code using HttpClient, but have also tried with PostSharp and HttpRequest.使用 HttpClient 显示我的代码,但也尝试过使用 PostSharp 和 HttpRequest。 I am using a local pfx certificate file which has a password.我正在使用具有密码的本地 pfx 证书文件。

In Postman:在邮递员中:

• Added the PFX cert to Client Certificates
• Authorization tab has username and password (Basic Auth)
• Authorization header automatically generates based on above ("Basic <encoded username/password>")
• Body is "{}"
    

Sends successfully (200).发送成功 (200)。

Using HttpClient:使用 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;
        }

This returns Unauthorized (401).这将返回未经授权 (401)。 The response text contains "Invalid user name or password."响应文本包含“无效的用户名或密码”。

Any thoughts on what might not be matching up between the two requests?关于两个请求之间可能不匹配的任何想法?

Have you tried using the Postman code snippets to auto-generate the code?您是否尝试过使用 Postman 代码片段自动生成代码? It uses the RESTSharp REST API client library for C#.它使用 C# 的 RESTSharp REST API 客户端库。

Click on the </> icon and choose "C# - RestSharp" and it should give you code.单击 </> 图标并选择“C# - RestSharp”,它应该为您提供代码。

在此处输入图片说明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM