Click here to Skip to main content
15,902,635 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am calling microsoft's token API for getting auth token.
I am using below code
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Clear();
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>(GrantType, ClientCredentials));
keyValues.Add(new KeyValuePair<string, string>("client_id", ClientId));
keyValues.Add(new KeyValuePair<string, string>("client_secret", ClientSecret));
keyValues.Add(new KeyValuePair<string, string>("scope", Scope));

var url = TokenUrl;

var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(keyValues));

I am getting following exception for this call when I deployed code on web server.
An error occurred while sending the request.</Message><Details>System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host


My clientId and secret are correct. This is working perfectly fine if I try this with Postman or even while debugging it locally.
But it is throwing exception when I deployed this code on web server.

Can anyone please guide me.

What I have tried:

I searched on google regarding this and tried following code before calling API:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

and
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Posted
Updated 23-Sep-21 6:27am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900