Click here to Skip to main content
15,942,710 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to fetch response via HTTPwebRequest with cer certificate in C#. I have imported the certificate with .cer extension to the Trusted Root certificate store. I am getting response null while fetching the response at GetResponse method

What I have tried:

My code is as below:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
               | SecurityProtocolType.Tls11
               | SecurityProtocolType.Tls12
               | SecurityProtocolType.Ssl3;

                ServicePointManager.Expect100Continue = true;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(txtRequestURL.Text);
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                request.Method = "POST";
                request.Accept = @"application/json";
                request.ContentType = @"application/json";
                Byte[] byteArray = encoding.GetBytes(txtReq.Text);
                request.ContentLength = byteArray.Length;
                if (chkRequestHeader.Checked)

                    request.Headers.Add("X-API-KEY", txtXAPIKey.Text);

                //request.Timeout = 1000 * Convert.ToInt32(txtResponseTimeOut.Text);

                  string certificatePath = @"D:\Cert.cer";
                  request.ClientCertificates.Add(new X509Certificate(certificatePath));

                 txtLog.Text += "btnInvoke_Click()-Adding Certificates Process Completed with Certificate path:"+certificatePath + Environment.NewLine;

               using (Stream stm = request.GetRequestStream())

                    stm.Write(byteArray, 0, byteArray.Length);

                    HttpWebResponse httpWebRes = (HttpWebResponse)request.GetResponse();
                    txtHTTPStatusCode.Text = Convert.ToString(httpWebRes.StatusCode);
                    using (StreamReader responseReader = new StreamReader(httpWebRes.GetResponseStream()))

                            txtResponse.Text = responseReader.ReadToEnd();
                        catch (Exception ex)

                            txtLog.Text += "btnInvoke_Click()-Fetching Response from Response Stream Failed with Exception: " + ex.Message
                               + Environment.NewLine + " with Inner Exception:" + ex.InnerException + Environment.NewLine + " at Stack Trace: " + ex.StackTrace + Environment.NewLine;

Updated 28-Nov-22 21:33pm
Richard Deeming 29-Nov-22 4:00am    
NB: Microsoft recommends that you don't set explicit security protocols in your code, and instead rely on the OS to pick the protocol to use:
Transport Layer Security (TLS) best practices with the .NET Framework - .NET Framework | Microsoft Learn[^]

1 solution

We can't tell: we can't run your code under identical conditions to you as we have no access to your system(s). But ... this is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900