0

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
GSerg
  • 76,472
  • 17
  • 159
  • 346
Pettanord
  • 81
  • 1
  • 9
  • You won't need to mess with the ServicePointManager so just omit that code. What problem are you experiencing when you run your c#? – Crowcoder Aug 29 '22 at 17:20
  • I get a error message saying that Origin is not allowed. It's not coming up in my vb code even though I run on the same machine from a local host. When I implemented it with vb code before I had the same problem but then added secureity and it worked?! – Pettanord Aug 29 '22 at 17:35
  • 1
    You can pass the ServicepointManager this way to your client. HttpClient _client = new HttpClient(); //specify to use TLS 1.2 as default connection System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; var baseUri = "https://localhost:4057/api/weatherforecast/"; – Chinmay T Aug 29 '22 at 17:44
  • Your c# project is probably running a different port than your vb project. Add your specific origin to your CORS configuration. – Crowcoder Aug 29 '22 at 17:45
  • If you are now using C# Asp.net Core, a browser-based client then you need to add the CORS setting. – Chinmay T Aug 29 '22 at 17:50
  • How about this row? ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications – Pettanord Aug 29 '22 at 17:50
  • More details on CORS settings https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0 – Chinmay T Aug 29 '22 at 17:50
  • System.Net.ServicePointManager.ServerCertificateValidationCallback = (s, ce, ca, p) => true; Should work for testing purpose. – Chinmay T Aug 29 '22 at 17:55
  • I don't have control over the api. I'm just doing calls to it. – Pettanord Aug 29 '22 at 18:01
  • If you are blocked by CORS then there is nothing you can do on the client side to fix it besides operating in an origin that works. Try changing your launch settings to use the same port that the vb project uses. – Crowcoder Aug 29 '22 at 18:03
  • The error message I get now is: Error: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch, RemoteCertificateChainErrors I've added the code suggested by Chinmay T to solve it but it still complains. Any suggestions – Pettanord Aug 30 '22 at 07:40
  • This error means the certificate validation issue, I suggest you could firstly ask the web api side which certificate version or else is needed from the client side. – Brando Zhang Aug 31 '22 at 02:28

0 Answers0