I have this request in VB.NET (NET framework) that I need to convert to C# ASP.NET Core Http Client. The code in VB.NET looks like this:
Public Function PostRundown(data As String) As String
Dim url = "https://url/import"
Dim result As String = ""
Dim httpRequest = CType(WebRequest.Create(url), HttpWebRequest)
httpRequest.Method = "POST"
httpRequest.ContentType = "application/x-www-form-urlencoded"
'Dim authInfo = "xxx:xxx"
Dim authInfo = config.NxtAuthInfo
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo))
httpRequest.Headers("Authorization") = "Basic " & authInfo
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12 Or SecurityProtocolType.Ssl3
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
Using streamWriter = New StreamWriter(httpRequest.GetRequestStream())
streamWriter.Write(data)
End Using
Dim httpResponse = CType(httpRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
result = streamReader.ReadToEnd()
End Using
Return result
End Function
In C# I've started to form the code like below:
public async Task<string> CreateString(string url, string data)
{
string authInfo = "xxx:xxx";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
_client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Authorization", "Basic " + authInfo);
_client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
//var sjson = JsonConvert.SerializeObject(obj);
var scontent = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
//HttpResponseMessage response = await _client.PostAsJsonAsync<T>(url, obj);
HttpResponseMessage response = await _client.PostAsync(url, scontent);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
//var newObj = JsonConvert.DeserializeObject<T>(json);
return json;
}
return "";
}
I'm not sure that the above code rightly represents the VB code. Also, I'm unsure how to implement the below lines in the HTTP client setting.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12 Or SecurityProtocolType.Ssl3
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications