I have a problem calling my ASP.NET Web API from a client application. Many questions regarding this topic were asked here but none of the answers solved my issue.
Problem:
When I try to call my API I get the following exception:
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Info:
Both projects (cleint and API) are based on .NET 4.5.2
In my test environment client and API are running on the same VM
Everything worked fine wihtout https
I created a selfsigned certificate for testing purposes but no browser shows a warning so it seems to be fine
Code:
HttpClient client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
client.BaseAddress = new Uri(apiBaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("call/CreateNew", call);
I tried several solutions provided in the answers of similar questions, but none of these worked so far:
Using .NET Framework 4.6 instread of 4.5.2
Specified the protocol with ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Tried ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; (just to be sure)
In another question someone suggested using Wireshark to further analyze the problem. I gave it a try but I have to admit that I did not really know what I was doing.
Anyway I found segments that said "ACKed segment that wasn't captured" and "Previous segment(s) not captured" of which the second contained data I actually tried to send to my API.
Can you give me some advice what to try next or how to fix this error?
Related
I have a custom class contained in a standard .net class library which makes a request to an external public facing api using the HttpClient.
When I instantiate the class and call the method via a standard .net console app, the expected result is returned.
However, executing the same code via a Xunit test produces the following exception:
'The underlying connection was closed: An unexpected error occurred on a send.'
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Both the test project and class library project framework are .Net Standard 4.8.
Most examples online make use of the WebApplicationFactory, documented here.
In my case I am not using ASP Core and I cannot use this class.
I am not that experienced in xunit and there is not much detail in the error message as to why this is occuring.
To try isolate the issue I tried running this piece of code directly in the test method and the same error occurrs.
Any suggestions/work arounds are much appreciated.
using (HttpClient httpClient = new HttpClient())
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = endpoint
};
request.Headers.Add("api-key", key);
using (HttpResponseMessage response = httpClient.SendAsync(request).Result)
{
var rawResponse = response.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<CustomResponse>(rawResponse);
}
}
I resolved the issue thanks to this post
Adding TLS 1.1 and 1.2 before the request was made worked
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
So We have windows service api that gets data then send to web using webclient
the problem is we have this certain branch that sends error while other branches api are working fine except for this one branch that sends error:
"The request was aborted: Could not create SSL/TLS secure channel"
i have added
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
yet the error still occured , please help and thankyou
heres the code
I'm guessing you already followed the top voted here: The request was aborted: Could not create SSL/TLS secure channel
Try to extend you tls protocols like this, so that it can fallback to previous versions if the server does not support them:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
If it doesn't work still, try the answer by User:APW with extra troubleshooting steps.
I'm trying to write C# code to scrape html code from a secure website (i.e. https://www.exampe.com).
I'm using Visual Studio 2017 with .Net Framework 4.5.2.
This is my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string html = reader.ReadToEnd();
}
When the above code is run, the following error is raised at line #2, GetResponse():
The request was aborted: Could not create SSL/TLS secure channel
When I use regular HTTP URL, then the above code works fine. It only breaks on HTTPS.
PS:
This website is external, meaning outside of our network and works fine when I view it via any browser. I assume it's got all necessary legitimate and valid certificates.
And by the way, my code works fine when I run it at home on a separate computer that's not connected to my company's network.
Please help!
This could be a TLS 1.2 problem. You have to tell C# to use TLS 1.2:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
add this code before your requests.
I found an answer to my question. All that needs to be done is to add the following line of code before creating a request:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
... and the rest is same as I had originally.
Now my app works great!
Thank you!
I am trying to call a Web API using HttpWebRequest(Console Application).
To upload the file, I am using the code snippet provided by #Cristian Romanescu ont this question Upload files with HTTPWebrequest (multipart/form-data)
If I set the req.ProtocolVersion as HttpVersion.Version10,I get Bad request when I try to do req.GetResponseStream().
If i set the req.ProtocolVersion as HttpVersion.Version11,I get Could not create SSL/TLS secure channel. when i try to do req.GetResponseStream().
If tried to post the data using POSTMAN, but even Postman says Could not get any response".
If I try to hit the URL using IE-11 I get HTTP 404.[I know i am not posting the actual file], but Chrome displays the custom/appropriate error message.
I tried the solutions already provided on stackoverflow, but unfortunately they do not solve my problem.
Thankyou.
Which solution you have tried? It's worth trying the following if you haven't already - write following before you actually invoke the service:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Two things that I was doing wrong.
The Server wanted date in yyyy-MM-ddTHH:mm:ss, I was providing the date in yyyy-MM-ddTHH:mm:ss.ssss Format(DateTime.UtcNow.ToString("o")). This was the cause of Could not create SSL/TLS secure channel
The server wanted the parameters in request body as well. I had passed the parameters only as query string. This was the cause of HTTP 404
In the process, I had asked a guy outside my team to help. He had asked me to see if there were any SSL related errors. To do this he asked me to add
System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); and define AcceptAllCertifications, which was not the case. So to resolve the issue, I had to take care of the things mentioned above.
Try to create self signed certificate from your server and add it to your client machine.
Create self signed certificate (Server side)
Import self signed certificate (Client side)
We've just launched a new service, which we're having trouble connecting to from a very basic c# console app when targeting the .Net 4.5 framework.
We first found the problem in an ASP MVC site, but have broken it down into the simplest of simple console apps to help isolate the problem
Code snippet (there isn't anything else):
string myURL = #"https://<myurl>.com/<myurl>";
using (var httpClient = new HttpClient())
{
var request = (HttpWebRequest)WebRequest.Create(myURL);
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "text/xml";
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
...
}
else
{
...
}
}
}
What happens
Web Exception - Underlying Connection Closed.
Thrown on the call to GetRequest
Service Information
HTTPS service
SHA-256.
Other differences
Examining the request variable in the intermediate window before it is sent shows no difference.
Examining the request variable after the call has been attempted shows one difference - System.Net.HttpWebRequest.Pipelined is true in the successful attempt, false in the failed attempt.
Setup Essentials
Load balancer, balancing between two API's hosted in IIS.
Has it ever worked?
Yes!
If the URL is dropped into a browser - it works.
If I recompile this code targeting the .net 4.6 framework - it works.
If I connect directly to the site in IIS (over http) it works.
What am I asking
What could be causing this problem?
Have you seen similar and have suggestions for possible remedies?
What further steps would you take to help debug / solve the issue.
How would changing .Net framework version to 4.6 affect the HttpClient or the HttpWebRequest?"
Thanks,
Al.
This is usually caused by the server using TLS v1.2. I think Net4.5 defaults to TLS v1.1, so you must add this to your code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;