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

I'm using the WCF4.0 template -REST. I'm trying to make a method that uploads a file using a stream.

The problem always occur at

Stream serverStream = request.GetRequestStream();

Class for streaming:

namespace LogicClass
{
    public class StreamClass : IStreamClass
    {
        public bool UploadFile(string filename, Stream fileStream)
        {
            try
            {
                FileStream fileToupload = new FileStream(filename, FileMode.Create);
                byte[] bytearray = new byte[10000];
                int bytesRead, totalBytesRead = 0;
                do
                {
                    bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
                    totalBytesRead += bytesRead;
                } while (bytesRead > 0);

                fileToupload.Write(bytearray, 0, bytearray.Length);
                fileToupload.Close();
                fileToupload.Dispose();
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
            return true;
        }
    }
}

REST project:

[WebInvoke(UriTemplate = "AddStream/{filename}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStream(string filename, System.IO.Stream fileStream)
{
    LogicClass.FileComponent rest = new LogicClass.FileComponent();
    return rest.AddStream(filename, fileStream);
}

Windows Form project: for testing

private void button24_Click(object sender, EventArgs e)
{
    byte[] fileStream;
    using (FileStream fs = new FileStream("E:\\stream.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        fileStream = new byte[fs.Length];
        fs.Read(fileStream, 0, (int)fs.Length);
        fs.Close();
        fs.Dispose();
    }

    string baseAddress = "http://localhost:3446/File/AddStream/stream.txt";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
    request.Method = "POST";
    request.ContentType = "text/plain";
    Stream serverStream = request.GetRequestStream();
    serverStream.Write(fileStream, 0, fileStream.Length);
    serverStream.Close();
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        int statusCode = (int)response.StatusCode;
        StreamReader reader = new StreamReader(response.GetResponseStream());
    }
}

I've turned off the firewall and my Internet connection, but the error still exists. Is there a better way of testing the uploading method?

Stack trace:

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)

This question is related to c# wcf rest httpwebrequest

The answer is


Introduction: I have encountered such problem when was testing my fist network app. I created: Client and Server then I ran client and suddenly exception was thrown, indeed it blocks the connection, because the port is not being listened!

Error: My port was not listened by the server, because server was down.

Solution: Run the Server first, so the port will be listened by server and once client tries to connect the server will handle that.


For my case, I had an Angular SLA project template with ASP.NET Core.

I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.

enter image description here


The problem, in this case, wasn't connected with the Firewall blocking the connection.

It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.


For more information, check the official Microsoft documentation.


You must set up your system proxy You have to go through this path controlpanel>>internet option>>connnection>>LAN settings>> proxy no tik:use proxy server


I got a similar error message like TCP error code 10061: No connection could be made because the target machine actively refused it in my current project. I find this 10061 error code cannot distinguish the case that the service endpoint is not started and the case that it is blocked by the firewall. Often, the firewall can be switched off, but the problem is still there.

You can test your code in the below two ways.

  1. Insert code to get time A that service is started and time B that client sends the request to the server. If B is earlier than A, it can cause this problem.
  2. Change your server port to another port that is also available in the system. You will find the same error code reported.

Above is my fix. It works on my machine. I hope it helps!


With this error I was able to trace it, thanks to @Yaur, you need to basically check the service (WCF) if it's running and also check the outbound and inbound TCP properties on your advance firewall settings.


I had a similar issue. In my case VPN proxy app such as Psiphon ? changed the proxy setup in windows so follow this :

in Windows 10, search change proxy settings and turn of use proxy server in the manual proxy


You don't have to restart the PC. Restart IIS instead.

Run -> 'cmd'(as admin) and type "iisreset"


Check if any other program is using that port.

If an instance of the same program is still active, kill that process.


With similar pattern, my rest client is calling the service API, the service called successfully when debugging, but not working on the published code. Error was: Unable to connect to the remote server.

Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it serviceIP:443 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)

Resolution: Set the proxy in Web config.

<system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="http://proxy_ip:portno/" usesystemdefault="True"/>
    </defaultProxy>
</system.net>

Make Sure all services used by your application are on, which are using host and port to utilize them . For e.g, as in my case, This error can come, If your application is utilizing a Redis server and it is not being able to connect to it on given port and host, thus producing this error .


I also faced problem in .Net Remoting Service in C#.

I got it solved in 3 steps:

  1. Change Port of Protocol in all the files whereever it is being used.
  2. Run your Host Server Program and make it active.
  3. Now run your client program.

I could not restart IIexpress. This is the solution that worked for me

  1. Cleaned the build
  2. Rebuild

I had the same problem on my web server "No connection could be made because the target machine actively refused it 161.x.x.235:5672". I asked the Admin to open the port 5672 on the web server, then it worked fine.


I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:

HTTP could not register URL http://+:12345/Foo.svc/]. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258


Check whether the port number in file Web.config of your webpage is the same as the one that is hosted on IIS.


If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.

I use this tool to do this; it automates all those cumbersome steps.


I had a similar problem rejecting localhost and 127.0.0.1. cmd(admin) netstat -anb found the port running on 169.254.80.80 (dont know were that ip came from because my network ip was 10.0.0.5. after putting in this IP it worked. This Gives correct IP:

IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress.ToString());

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 wcf

Create a asmx web service in C# using visual studio 2013 WCF Exception: Could not find a base address that matches scheme http for the endpoint WCF Service, the type provided as the service attribute values…could not be found WCF error - There was no endpoint listening at How can I pass a username/password in the header to a SOAP WCF Service The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM' Content Type application/soap+xml; charset=utf-8 was not supported by service The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) maxReceivedMessageSize and maxBufferSize in app.config how to generate a unique token which expires after 24 hours?

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request