[c#] No connection could be made because the target machine actively refused it

I try to connect to a web service hosted on a different server using the WebRequest Class. The web service returns a string as a Response. While doing so I get an Error:

"System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it"

System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 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, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream() at Limoallover.InsertSoapEnvelopeIntoWebRequestUS(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) at Limoallover.dawUpdateDriverStatus(String apiId, String apiKey, String idTrip, String tripCode, String statusCode) at Limoallover.UpdateJobStatus(String Lat, String Lng, Int32 DriverID, Int32 nJobStatus, Int32 nJobId, String CompanyID, String idTrip, String tripCode, String statusCode)

private  HttpWebRequest CreateWebRequestUS(string url, string action)
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Headers.Add("SOAPAction", action);
    webRequest.ContentType = "text/xml;charset=\"utf-8\"";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    return webRequest;

private  XmlDocument CreateSoapEnvelopeUS(string apiId, string apiKey, string idTrip, string tripCode, string statusCode)
    XmlDocument soapEnvelop = new XmlDocument();

    string xml = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";

    xml = xml + @"<soap:Body>";
    xml = xml + "<UpdateTripStatus xmlns=\"https://book.mylimobiz.com/api\">";
    xml = xml + @"<apiId>" + apiId + "</apiId>";
    xml = xml + @"<apiKey>" + apiKey + "</apiKey>";
    xml = xml + @"<idTrip>" + idTrip + "</idTrip>";
    xml = xml + @"<tripCode>" + tripCode + "</tripCode>";
    xml = xml + @"<statusCode>" + statusCode + "</statusCode>";
    xml = xml + @"</UpdateTripStatus>";
    xml = xml + @"</soap:Body>";
    xml = xml + @"</soap:Envelope>";

    return soapEnvelop;

private static void InsertSoapEnvelopeIntoWebRequestUS(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
    using (Stream stream = webRequest.GetRequestStream())

This question is related to c# asp.net .net sockets

The answer is

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

Add new WebProxy() for the proxy setting , where you are creating a web request.

Example :-

  string url =  "Your URL";
  System.Net.WebRequest req = System.Net.WebRequest.Create(url);
  req.Proxy = new WebProxy();
  System.Net.WebResponse resp = req.GetResponse();

Where req.Proxy = new WebProxy() handle the proxy setting & helps the code to work fine.

I had the same issue with a site which previously was running fine. I resolved the issue by deleting the temporary files from C:\WINDOWS\Microsoft.NET\Framework\v#.#.#####\Temporary ASP.NET Files\@projectName\###CC##C\###C#CC

The issue disappeared for me when I started Fiddler. Was using it on my machine before having the issue. Probably something with Fiddler being proxy.

If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)

Delete Temp files by run > %temp%

And Open VS2015 by run as admin,

it works for me.

Had the same problem, it turned out it was the WindowsFirewall blocking connections. Try to disable WindowsFirewall for a while to see if helps and if it is the problem open ports as needed.

I had a similar issue, trying to run a WCF-based HttpSelfHostServer in Debug under my VisualStudio 2013. I tried every possible direction (turn off firewall, disabling IIS completely to eliminate the possibility localhost port is taken by some other service, etc.).

Eventually, what "did the trick" (solved the problem) was re-running VisualStudio 2013 as Administrator.


There is a firewall blocking the connection or the process that is hosting the service is not listening on that port. Or it is listening on a different port.

The exception message says you're trying to connect to the same host (, while you're stating that your server is running on a different host. Besides the obvious bugs like having "localhost" in the url, or maybe some you might want to check your DNS settings.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version= No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to .net

You must add a reference to assembly 'netstandard, Version= How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to sockets

JS file gets a net::ERR_ABORTED 404 (Not Found) mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 TypeError: a bytes-like object is required, not 'str' Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED No connection could be made because the target machine actively refused it Sending a file over TCP sockets in Python socket connect() vs bind() java.net.SocketException: Connection reset by peer: socket write error When serving a file How do I use setsockopt(SO_REUSEADDR)?