I'm working with the APIs on which I have to send a request to get an authentication key. I tried many way but always I'm getting the same exception as follows:
the underlying connection was closed an unexpected error occurred on a send.
Here is my code for reference:
public AuthTokenReponse GetAuthToken(IClientConfiguration clientConfiguration)
{
try
{
_logger.Info($"Getting Authentication Token");
var client = new RestClient(_portalConfiguration.ApiAuthHostUrl);
client.Proxy = new WebProxy();
var request = new RestRequest(Method.POST);
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
request.AddHeader("client_id", clientConfiguration.ApiClientId);
request.AddHeader("client_secret", clientConfiguration.ApiClientSecret);
request.AddHeader("Gstin", clientConfiguration.ApiGstin);
request.AddHeader("user_name", clientConfiguration.ApiUserName);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.RequestFormat = DataFormat.Json;
var obj = new AuthRequestDto();
var appKey = GenerateAppKey();
obj.Data = new AuthRequestDto.DataDto
{
UserName = clientConfiguration.ApiUserName,
Password = EncryptAsymmetric(clientConfiguration.ApiPassword, clientConfiguration.ApiPublicKey),
AppKey = Encrypt(appKey, clientConfiguration.ApiPublicKey),
ForceRefreshAccessToken = true
};
request.AddJsonBody(new
{
data = obj.Data
});
_logger.Error($"Request Json : {JsonConvert.SerializeObject(request)}");
IRestResponse response = client.Execute(request);
//Here I'm getting the error in my Log file.
_logger.Error($"Response Error {response.ErrorMessage}");
_logger.Error($"Response Content {response.Content}");
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
var result = JsonConvert.DeserializeObject<AuthTokenReponse>(response.Content);
if (result.Status > 0)
{
result.SekToken = DecryptBySymmetricKey(result.Data.Sek, appKey);
return result;
}
_logger.Error($"Error while getting auth token {response.Content} {response.StatusCode}");
}
else if (response != null)
{
_logger.Error($"Error while getting auth token {response.Content} Status Code: {response.StatusCode}");
}
else
{
_logger.Error($"Error while getting auth token {response.Content} , Reason unknown.");
}
return null;
}
catch (Exception ex)
{
_logger.Error($"Error while getting auth token", ex);
return null;
}
}
Options I have already tried:
If you have any solution then please let me know.
Everything was fine, there was a restriction to the client's server that every IP used in calling the API, need to be registered on their portal. The error was raising because IP was not registered.
So if anyone face the similar issue, then please try this solution too.