Search code examples
c#posthttpswindows-serviceshttpwebrequest

C# HttpWebRequest on Windows Service: Changing any Property in Request does't give a Effect


I have written an Windows WCF Service (running as LocalSystem) getting Requests from a webserver and one of the verification steps for the data is, to send them again to the Webserver (https), which is doing the work.

Now i am trying to send the request with the "HttpWebRequest" class.

Following performs my request: ( Parameter: string a_Body contains stringlyfied Json )

// Accept all certificates
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
    return true;
};

// Encode given Json coded Data to Bytearray
byte[] formData = Encoding.UTF8.GetBytes( a_Body );

HttpWebRequest req = WebRequest.Create(new Uri( ApiVerifyUrl )) as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.Accept = "application/json";
req.ContentType = "application/json";

// Test Header, to see, if it would be set!
req.Headers.Add("X-Test", "Test123");

req.ContentLength = formData.Length;

// fiddler connection
req.Proxy = new WebProxy("[ip]", [port]);

using (Stream post = req.GetRequestStream()) // <- throws error ( see log below )
{
    post.Write( formData, 0, formData.Length );
    post.Close();
}

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

Im also catching an Exception, whis is thrown by:

using (Stream post = req.GetRequestStream())

Details to Exception:

[21.11.2018 08:36:21] Emergency:  
An exception "WebException" occurred:  
 - Message:   
   Die zugrunde liegende Verbindung wurde geschlossen: Unerwarteter Fehler beim Senden..  
   (= The Connection was closed: unexpected error)  
 - Source:   
   System  
 - Target:   
   System.IO.Stream GetRequestStream(System.Net.TransportContext ByRef)  
 - Stack Trace:   
   bei System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)  
   bei System.Net.HttpWebRequest.GetRequestStream()  
   bei Intrasearch.Service.HttpServer.ValidateRequestByApi(String a_Body)   
 - InnerException: "IOException":  
    - Message:   
      Von der Übertragungsverbindung können keine Daten gelesen werden: Eine   vorhandene Verbindung wurde vom Remotehost geschlossen.
      (= Data cant be read from the Connection: Remotehost closed the connection)
    - Source:   
      System  
    - Target:   
      Int32 Read(Byte[], Int32, Int32)    
    - Stack Trace:   
      bei System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)  
      bei System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)  
      bei System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,   AsyncProtocolRequest asyncRequest)  
      bei System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)   
      bei System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)  
      bei System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)  
      bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)  
      bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)  
      bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)  
      bei System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)  
      bei System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)  
      bei System.Net.ConnectStream.WriteHeaders(Boolean async)   
 - InnerException: "SocketException":
       - Message: 
         Eine vorhandene Verbindung wurde vom Remotehost geschlossen 
         (= An Connection was closed by the remotehost) 
       - Source:   
         System  
       - Target:   
         Int32 Read(Byte[], Int32, Int32)  
       - Stack Trace:  
         bei System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 

Now i am asking: Why are my Attributes not set properly, so that the request can't establish an proper connection? The same Code runs in an console application with the same Webserver. I am searching for days by now.


Solution

  • I have used an old Version of .Net Framework (4.0), where Tls 1.2 was not supported. Our Server has restricted any connection without Tls 1.2, so this error occured.

    I've simply changed the .Net Version to 4.5 and added:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    And now it works!