73

I'm working on an integration with Alternative Payments using their hosted page integration. Their C# SDK does not have this integration available at the moment, but as you can see it's pretty simple and I made a small class to send the post request and get the JSON response.

I tested the json object I'm sending on PostMan and cURL and both work, also the authentication header, so I think they are not the problem. Here is the constructor of my class:

public AlternativePaymentsCli(string apiSecretKey)
{
    this._apiSecretKey = apiSecretKey;

    _httpClient = new HttpClient();
    _httpClient.DefaultRequestHeaders.Accept
        .Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var authInfo = _apiSecretKey;
    authInfo = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:", _apiSecretKey)));

    // The two line below because I saw in an answer on stackoverflow.
    _httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive"); 
    _httpClient.DefaultRequestHeaders.Add("Keep-Alive", "3600");

    _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Anything.com custom client v1.0");
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);

}

And the method where I'm posting the data:

public string CreateHostedPageTransaction(HostedPageRequest req) 
{
    var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

    // I send this same json content on PostMan and it works. The json is not the problem
    var content = new StringContent(JsonConvert.SerializeObject(req, settings), Encoding.UTF8, "application/json");
    var response = _httpClient.PostAsync(this._baseUrl + "/transactions/hosted", content).Result;
    var responseText = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();

    if (response.IsSuccessStatusCode)
        return responseText;

    return "";
}

Then I get this error: An existing connection was forcibly closed by the remote host, at the PostAsync line. This is the error details:

[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
   System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) +8192811
   System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult) +47

[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
   System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) +294
   System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar) +149

[WebException: The underlying connection was closed: An unexpected error occurred on a send.]
   System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) +324
   System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) +137

[HttpRequestException: An error occurred while sending the request.]

I'm using C# 4.5, Asp.Net MVC. I've been reading answers for the same error and none of them solved my issue so far. What am I missing in this code?

Thanks for any help

11
  • 16
    Just a nice tip, using var for everything will make your coworkers hate you. Only use var when the type is apparent (i.e var date = new DateTime();) its very clearly a DateTime. However var response = _httpClient.PostAsync(this._baseUrl + "/transactions/hosted", content).Result; is not clear because .Result is a property and not implicit what type it is.
    – maccettura
    Commented Sep 14, 2017 at 15:36
  • 25
    @maccettura on the contrary, using var makes the code a lot cleaner. There is no ambiguity about what the type is unless you write really long methods, in which case you should really, really break them apart. Coworkers will hate you if you write methods that are so long they can't see what the types are Commented Sep 14, 2017 at 15:42
  • 6
    @PanagiotisKanavos var only makes code cleaner when the type is implied, using var everywhere (even in cases where the type is not implied) is simply poor programming.
    – maccettura
    Commented Sep 14, 2017 at 15:45
  • 10
    @maccettura as for .Result, coworkers will hate anyone that blocks an asynchronous call with .Wait() or .Result. The return type is known anyway. It's HttpResponseMessage. Seeing the name won't help you as you'll have to use intellisense anyway to find which methods to use Commented Sep 14, 2017 at 15:45
  • 4
    @maccettura which, for example, is why functional languages use type inference instead of specifying the type explicitly You may not be familiar with type inference. That doesn't make it poor programming. On the other hand a call to .Result should raise anyone's hackles Commented Sep 14, 2017 at 15:46

5 Answers 5

208

I don't see in your code sample where you are setting the value of _baseUrl, but I'm assuming that is being done somewhere. I'm also assuming that since this related to payments, the URL is HTTPS. If the remote host has disabled TLS 1.0 and your connection is coming in as TLS 1.0, it could cause that behavior. I know C# 4.6 has TLS 1.0/1.1/1.2 support enabled by default, but I think C# 4.6 still defaults to only SSL3/TLS 1.0 even though TLS 1.1 and 1.2 are supported. If this is the cause of the issue, you can manually add TLS 1.1 and 1.2 to the enabled values using the following code.

System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
12
  • 1
    thank you very much Sir, you solved my issue. Locally I run a fake HTTPS, chrome warn me that's the site is unsafe etc.. that must be it. Commented Sep 14, 2017 at 16:00
  • 2
    You do not have to alter code to enable this for applications that are currently running in prod: learn.microsoft.com/en-us/officeonlineserver/… Commented Jan 25, 2018 at 17:51
  • 1
    yeah, is this only needed within the app domain (using in a worker role) or do I need to set this per HttpClient request? Commented Jun 17, 2018 at 6:51
  • 2
    @Ruchira and NathanTregillus You can set it per request (adding the code before you send your request), or you can set it once for the entire application by setting it Application_Start() in Global.asax.cs Commented Jun 18, 2018 at 13:38
  • 2
    Thanks @PaulPearce. I ended up adding this to Global.asax. Used "using System.Net;" add the top to support ServicePointManager and SecurityProtocolType.
    – Ruchira
    Commented Jun 20, 2018 at 4:59
21

If you are using .Net 4.0 then SecurityProtocolType.Tls11 and SecurityProtocolType.Tls2 are not defined so instead you can use the hard coded value below.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

0
13

It is possible to solve the issue without any changes in the code, as described in this excellent answer to a similar question:

Retarget the web project to .Net 4.6+, then update web.config as the following:

<system.web>
  <compilation targetFramework="4.6" /> 
  <httpRuntime targetFramework="4.6" /> 
</system.web>
3

For me this error was caused by forgetting to configure the proxy server. Using the following code to construct the HttpClient solved it for my .NET 4.7.2 application:

var httpClientHandler = new HttpClientHandler { Proxy = WebRequest.GetSystemWebProxy() };
var httpClient = new HttpClient(httpClientHandler);

Hope this helps someone.

2

This worked for me, the first line ensures the protocols ssl3 and TLS1.2, and the second line ignores any potential certificate errors (ignore and continue - like expired certs.):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=  (sender, certificate, chain, sslPolicyErrors) => true;
2
  • 1
    Hello and welcome to the community, try using the formatting tools in the text editor to make your answer look better, and easier to read. The Code formatter is especially useful and it will work wonders. Commented Feb 24, 2020 at 18:37
  • 1
    This should not be considered as a production solution. Ignoring the Certificate checks invalidates the security of SSL. This is fine in a test environment. Commented Nov 23, 2021 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.