1

Having a hard time converting a successful Postman request to a successful request in C#. Showing my code using HttpClient, but have also tried with PostSharp and HttpRequest. I am using a local pfx certificate file which has a password.

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).

Using 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). The response text contains "Invalid user name or password."

Any thoughts on what might not be matching up between the two requests?

6
  • 1
    Are you hitting a redirect with your request? By design, those aren't sent following a redirect request from the server Commented Oct 11, 2021 at 22:34
  • You could try to intercept your request (and the postman request) with a sniffer (eG wireshark or fiddler) to see if you're actually transmitting the same values. AFAIK setting the SslProtocols is not needed, just leave that line out. Furthermore the ServerCertificateCustomValidationCallback should result (for the server) into an expected hash. That being said; you mention the password should be encoded ("Basic <encoded password>"), but not the username although you encode both..? Commented Oct 11, 2021 at 22:36
  • And indeed what @ESG states, redirects will strip all header values Commented Oct 11, 2021 at 22:37
  • 1
    @ESG I considered redirects--I have turned off "Automatically follow redirects" in Postman and still get a success response (200). Commented Oct 12, 2021 at 11:22
  • @riffnl Username/password should both be encoded--I will edit the question. Not sure what you mean about ServerCertificateCustomValidationCallback--could you elaborate? I'll work towards getting the two requests captured in Fiddler. Commented Oct 12, 2021 at 11:32

2 Answers 2

8

Have you tried using the Postman code snippets to auto-generate the code? It uses the RESTSharp REST API client library for C#.

Click on the </> icon and choose "C# - RestSharp" and it should give you code.

enter image description here

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

Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate that it has RestSharp but the issue is I am looking for the HttpClient code instead.
This is brilliant, thanks! @AmirHajiha, as of Postman v10.24.25, the drop-down actually has the "C# - HttpClient" option.
2

It is available in newer postman version(released in 10.10.6) https://github.com/postmanlabs/postman-code-generators/pull/453

2 Comments

Your information is indeed useful. Thank you. However, "It is available" with merely a link is insufficient for me to up vote your answer. You need to better position your answer within the context of the question asked.
@ScottWelker, the question was already answered by w4dd325 . During the time I answered the question, I was using the older version of Postman which did not have the "Export to C# - RestSharp" functionality hence I just wanted to inform others that only the newer version of Postman had the functionality

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.