The underlying connection was closed: (HttpWebRequest) - C#












1















I am writing a code to authenticate the username and password through the POST request but I am getting an error which is saying that "The underlying connection was closed".



I am trying to convert my old code with GET request to new code with POST request.



My GET code which is working fine (Old Code):



string url = "https://www.example.com/?username=" + username + "&password=" + password;

XmlDocument xmldoc = new XmlDocument();
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

xmldoc.Load(url);
XmlNode name = xmldoc.SelectSingleNode("/Node/Name");


My POST request Code which is throwing an error (New Code):



var request = (HttpWebRequest)WebRequest.Create("https://www.example.com/authenticate.aspx");
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var postData = "user=username";
postData += "&pass=password";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Error:



System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm
at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte& thumbPrint)
at System.Net.Security.SecureChannel.GenerateToken(Byte input, Int32 offset, Int32 count, Byte& output)
at System.Net.Security.SecureChannel.NextMessage(Byte incoming, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartSendBlob(Byte incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at OdlumBrown.Members.AuthenticateUser(String username, String password) in c:Websiteexample.comApp_CodeMembership.cs:line 148









share|improve this question

























  • So, add back the ServicePointManager.ServerCertificateValidationCallback. Since it's an authentication service, I assume it's using an Https connection. Otherwise, why setting ServicePointManager.SecurityProtocol if it's not required (for an Http connection). If you don't actually need to verify the server certificates of pass on a new one, just return true.

    – Jimi
    Nov 24 '18 at 0:27













  • First thing to find out: Uses the server http or https. If http: No SecureProtocol or Certificate is needed. If https: Change url to https, add ServerCertificateValidationCallback as @jimi mentioned.

    – H.G. Sandhagen
    Nov 24 '18 at 8:02











  • @H.G.Sandhagen I am using https for the request. I have updated that in my comment

    – orbnexus
    Nov 26 '18 at 17:47
















1















I am writing a code to authenticate the username and password through the POST request but I am getting an error which is saying that "The underlying connection was closed".



I am trying to convert my old code with GET request to new code with POST request.



My GET code which is working fine (Old Code):



string url = "https://www.example.com/?username=" + username + "&password=" + password;

XmlDocument xmldoc = new XmlDocument();
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

xmldoc.Load(url);
XmlNode name = xmldoc.SelectSingleNode("/Node/Name");


My POST request Code which is throwing an error (New Code):



var request = (HttpWebRequest)WebRequest.Create("https://www.example.com/authenticate.aspx");
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var postData = "user=username";
postData += "&pass=password";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Error:



System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm
at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte& thumbPrint)
at System.Net.Security.SecureChannel.GenerateToken(Byte input, Int32 offset, Int32 count, Byte& output)
at System.Net.Security.SecureChannel.NextMessage(Byte incoming, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartSendBlob(Byte incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at OdlumBrown.Members.AuthenticateUser(String username, String password) in c:Websiteexample.comApp_CodeMembership.cs:line 148









share|improve this question

























  • So, add back the ServicePointManager.ServerCertificateValidationCallback. Since it's an authentication service, I assume it's using an Https connection. Otherwise, why setting ServicePointManager.SecurityProtocol if it's not required (for an Http connection). If you don't actually need to verify the server certificates of pass on a new one, just return true.

    – Jimi
    Nov 24 '18 at 0:27













  • First thing to find out: Uses the server http or https. If http: No SecureProtocol or Certificate is needed. If https: Change url to https, add ServerCertificateValidationCallback as @jimi mentioned.

    – H.G. Sandhagen
    Nov 24 '18 at 8:02











  • @H.G.Sandhagen I am using https for the request. I have updated that in my comment

    – orbnexus
    Nov 26 '18 at 17:47














1












1








1


1






I am writing a code to authenticate the username and password through the POST request but I am getting an error which is saying that "The underlying connection was closed".



I am trying to convert my old code with GET request to new code with POST request.



My GET code which is working fine (Old Code):



string url = "https://www.example.com/?username=" + username + "&password=" + password;

XmlDocument xmldoc = new XmlDocument();
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

xmldoc.Load(url);
XmlNode name = xmldoc.SelectSingleNode("/Node/Name");


My POST request Code which is throwing an error (New Code):



var request = (HttpWebRequest)WebRequest.Create("https://www.example.com/authenticate.aspx");
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var postData = "user=username";
postData += "&pass=password";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Error:



System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm
at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte& thumbPrint)
at System.Net.Security.SecureChannel.GenerateToken(Byte input, Int32 offset, Int32 count, Byte& output)
at System.Net.Security.SecureChannel.NextMessage(Byte incoming, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartSendBlob(Byte incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at OdlumBrown.Members.AuthenticateUser(String username, String password) in c:Websiteexample.comApp_CodeMembership.cs:line 148









share|improve this question
















I am writing a code to authenticate the username and password through the POST request but I am getting an error which is saying that "The underlying connection was closed".



I am trying to convert my old code with GET request to new code with POST request.



My GET code which is working fine (Old Code):



string url = "https://www.example.com/?username=" + username + "&password=" + password;

XmlDocument xmldoc = new XmlDocument();
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

xmldoc.Load(url);
XmlNode name = xmldoc.SelectSingleNode("/Node/Name");


My POST request Code which is throwing an error (New Code):



var request = (HttpWebRequest)WebRequest.Create("https://www.example.com/authenticate.aspx");
ServicePointManager.ServerCertificateValidationCallback += new
RemoteCertificateValidationCallback(customXertificateValidation);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var postData = "user=username";
postData += "&pass=password";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Error:



System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm
at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte& thumbPrint)
at System.Net.Security.SecureChannel.GenerateToken(Byte input, Int32 offset, Int32 count, Byte& output)
at System.Net.Security.SecureChannel.NextMessage(Byte incoming, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartSendBlob(Byte incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at OdlumBrown.Members.AuthenticateUser(String username, String password) in c:Websiteexample.comApp_CodeMembership.cs:line 148






c# authentication post get httpwebrequest






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 17:48







orbnexus

















asked Nov 23 '18 at 22:21









orbnexusorbnexus

399425




399425













  • So, add back the ServicePointManager.ServerCertificateValidationCallback. Since it's an authentication service, I assume it's using an Https connection. Otherwise, why setting ServicePointManager.SecurityProtocol if it's not required (for an Http connection). If you don't actually need to verify the server certificates of pass on a new one, just return true.

    – Jimi
    Nov 24 '18 at 0:27













  • First thing to find out: Uses the server http or https. If http: No SecureProtocol or Certificate is needed. If https: Change url to https, add ServerCertificateValidationCallback as @jimi mentioned.

    – H.G. Sandhagen
    Nov 24 '18 at 8:02











  • @H.G.Sandhagen I am using https for the request. I have updated that in my comment

    – orbnexus
    Nov 26 '18 at 17:47



















  • So, add back the ServicePointManager.ServerCertificateValidationCallback. Since it's an authentication service, I assume it's using an Https connection. Otherwise, why setting ServicePointManager.SecurityProtocol if it's not required (for an Http connection). If you don't actually need to verify the server certificates of pass on a new one, just return true.

    – Jimi
    Nov 24 '18 at 0:27













  • First thing to find out: Uses the server http or https. If http: No SecureProtocol or Certificate is needed. If https: Change url to https, add ServerCertificateValidationCallback as @jimi mentioned.

    – H.G. Sandhagen
    Nov 24 '18 at 8:02











  • @H.G.Sandhagen I am using https for the request. I have updated that in my comment

    – orbnexus
    Nov 26 '18 at 17:47

















So, add back the ServicePointManager.ServerCertificateValidationCallback. Since it's an authentication service, I assume it's using an Https connection. Otherwise, why setting ServicePointManager.SecurityProtocol if it's not required (for an Http connection). If you don't actually need to verify the server certificates of pass on a new one, just return true.

– Jimi
Nov 24 '18 at 0:27







So, add back the ServicePointManager.ServerCertificateValidationCallback. Since it's an authentication service, I assume it's using an Https connection. Otherwise, why setting ServicePointManager.SecurityProtocol if it's not required (for an Http connection). If you don't actually need to verify the server certificates of pass on a new one, just return true.

– Jimi
Nov 24 '18 at 0:27















First thing to find out: Uses the server http or https. If http: No SecureProtocol or Certificate is needed. If https: Change url to https, add ServerCertificateValidationCallback as @jimi mentioned.

– H.G. Sandhagen
Nov 24 '18 at 8:02





First thing to find out: Uses the server http or https. If http: No SecureProtocol or Certificate is needed. If https: Change url to https, add ServerCertificateValidationCallback as @jimi mentioned.

– H.G. Sandhagen
Nov 24 '18 at 8:02













@H.G.Sandhagen I am using https for the request. I have updated that in my comment

– orbnexus
Nov 26 '18 at 17:47





@H.G.Sandhagen I am using https for the request. I have updated that in my comment

– orbnexus
Nov 26 '18 at 17:47












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453465%2fthe-underlying-connection-was-closed-httpwebrequest-c-sharp%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453465%2fthe-underlying-connection-was-closed-httpwebrequest-c-sharp%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'