Search code examples
c#system.net.httpwebrequest

HttpWebRequest.GetRequestStream() connection gets actively refused in executable but not in WPF standalone application


I am working with web server to make calls to its API via HttpWebRequests. I wrote a standalone WPF application for testing purposes and all of my requests were functioning correctly. When I referenced the working project file in my production application it is now returning that the request is being actively refused by the server.

public string Post(string xmlData, Transaction transaction)
{
        var result = "";

        try
        {
            var webReq = (HttpWebRequest)WebRequest.Create(BaseUrl);
            webReq.Accept = "application/xml";
            webReq.ContentType = "application/xml";
            webReq.Method = "POST";
            webReq.KeepAlive = false;
            webReq.Proxy = WebRequest.DefaultWebProxy;
            webReq.ProtocolVersion = HttpVersion.Version10;

            // If we passed in data to be written to the body of the request add it
            if (!string.IsNullOrEmpty(xmlData))
            {
                webReq.ContentLength = xmlData.Length;
                using (var streamWriter = new StreamWriter(webReq.GetRequestStream())) /**CONNECTION REFUSED EXCEPTION HERE**/
                {

                    streamWriter.Write(xmlData);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            else //Otherwise write empty string as body
            {
                webReq.ContentLength = 0;
                var data = "";
                using (var streamWriter = new StreamWriter(webReq.GetRequestStream()))
                {

                    streamWriter.Write(data);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }

            //Attempt to get response from web request, catch exception if there is one
            using (var response = (HttpWebResponse)webReq.GetResponse())
            {
                using (var streamreader =
                    new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException()))
                {
                    result = streamreader.ReadToEnd();
                }
            }

            return result;
        }
        catch (WebException e)
        {
            //Handle web exceptions here               
        }
        catch (Exception e)
        {
            //Handle other exceptions here
        }
    }

Has anyone else encountered this problem?


Solution

  • After reviewing your fiddler requests I can say that the reason is probably the IP address difference.

    You use 192.168.1.186:44000 first time and 192.168.1.86:44000 second time.