I have declared a class ClientClass which inherits from WebClient. I am using this class to define an HttpWebRequest object since I want to pass SSL certificate along with the request for client authentication.
public class ClientClass : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request = (HttpWebRequest)base.GetWebRequest(address);
request.ClientCertificates.Add(GetCertificate());
return request;
}
private static X509Certificate2 GetCertificate()
{
string certificateThumbprint = AADHelper.DecryptConfigurationSetting(ConfigHelper.CertificateThumbprint);
string thumbprint = certificateThumbprint;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
List<X509Certificate2> list = store.Certificates.Cast<X509Certificate2>().ToList();
X509Certificate2 clientCertificate = list.Find(c => c.Thumbprint != null && c.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase));
return clientCertificate;
}
}
Using UploadData Method of WebClient Class, I am able to send POST request and get response string. But I want to receive response headers also along with the string. I thought of using HttpWebResponse for response but I am unsure how I will be able to send post request.
My code for sending POST request is as follows:
using (var client = new ClientClass())
{
client.Headers.Add("content-type", "application/json");
client.Headers.Add("x-ms-tracking-id", TrackingId.ToString());
string rawResponse;
rawResponse = Encoding.ASCII.GetString(client.UploadData(Url, "POST", Encoding.Default.GetBytes(jsonString))); dataAccessLayer.InsertKeyReplacementKFSAudit(keyReplacementID, TrackingId, jsonString, rawResponse, request.User, startTime, endTime);
}
Could you help me with how I can read response headers as well. Thanks in advance.
You can use client.ResponseHeaders
to retrieve response headers.
try
{
rawResponse = Encoding.ASCII.GetString(client.UploadData(Url, "POST", Encoding.Default.GetBytes(jsonString)));
var responseHeaders = client.ResponseHeaders;
}
catch (WebException wex) // To handle error
{
// wex.Response.Headers // You can retrieve the headers
//((HttpWebResponse)wex.Response).StatusCode //You can handle StatusCode like this;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.