Основное соединение было закрыто: (HttpWebRequest) - C # - PullRequest
0 голосов
/ 24 ноября 2018

Я пишу код для аутентификации имени пользователя и пароля с помощью запроса POST, но я получаю сообщение об ошибке «Базовое соединение было закрыто».

Я пытаюсь преобразовать свой старый кодс запросом GET к новому коду с запросом POST.

Мой код GET, который работает нормально (Старый код):

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");

Код моего запроса POST, который выдает ошибку (Новый код):

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();

Ошибка:

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:\Website\example.com\App_Code\Membership.cs:line 148
...