Search code examples
c#.nethttpwebrequestscheduled-tasks

Web Request Fails in Console App when ran on Schedule Task schedule


We have a simple console app, written in C# .NET 4.0, that currently runs on a scheduled task. This console app simply takes files out of one directly on disk and then uploads them to an ASP.NET web site hosted on the same machine.

When this console is run on its triggered time it fails with the following exception:

Message: Unable to connect to the remote server
Stack Trace:    at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at Program.Main(String[] args) in Program.cs:line 69
Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 127.0.0.1:80
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

However, when we run the application manually it runs perfectly fine as well as when we go into Scheduled Tasks and run the task manually it will execute without error.

We have the host file currently configured for the domain it is trying to connect to that points back to the loopback IP which you can see in the exception. This is in place due to a firewall configuration that doesn't allow internal connections to the external IP.

Additional information on the Scheduled Task:

  • It is set to run under the admin credentials and with highest permissions.
  • It only runs once a day
  • It performs other operations without issue (Moving and renaming files)
  • The error occurs on HttpWebRequest.GetRequestStream()

Solution

  • This ended up being a very strange situation in the end and resolving a different issue ended up being what solved this one.

    What turned out happening was there ended up being a scheduled task that was running at the exact same time that was forcing an IIS Reset. Well the IIS Reset would hit and while it was trying to start back up this process would attempt to upload a file. The upload would of course fail with the above error message because there ended up being nothing listening on port 80 while IIS service was starting.

    The Scheduled task that was being run was an old fix for a different issue around releasing resources that would be consumed by IIS. It was under a different user so it required further digging to find. Once it was disabled the daily process ran without issue.