2

Before I get started

First let me apologize in advance if this is a duplicate question as there appear to be several questions related to 'Existing connection was forcible closed by the remote host', however I can't seem to get any help from these other questions as they same to be either related to FTP (not HTTP), seem to be caused to request length issues, or I simply don't understand the answer.

The Goal

I am trying to use a System.Net.WebRequest to make a REST API call to the third party service mobile application push service Parse.com. Despite the fact that this request works roughly 95% of the time, it will intermittently throw a System.Net.Web exception.

Some similar posts that I have read indicate that this might have something to do with the size of the request being sent, however this seems someone unlikely to me since the requests are roughly the same size each time (Note: this might be an ignorant assumption).

Here is the method I am using to make the Web Request

public static WebResponse SendPushHttpRequest(
            string payload, string apiID, string apiKey)
    {

        WebRequest request = WebRequest.Create("https://some.api.com/1/endpoint");

        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers["Application-Id"] = apiID;
        request.Headers["API-Key"] = apiKey;

        byte[] buffer =
            System.Text.Encoding.GetEncoding("UTF-8").GetBytes(payload);
        //string result = Convert.ToBase64String(buffer);
        Stream reqstr = request.GetRequestStream();
        reqstr.Write(buffer, 0, buffer.Length);
        reqstr.Close();

        try
        {
            using (WebResponse response = request.GetResponse())
            {
                return response;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Here is the System.Net.Web Exception that is thrown The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."} System.SystemException {System.IO.IOException}

Exception Status ReceiveFailure

Stack Trace

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) 

Response from the Web Server

 GenericParameterAttributes '(((System.Reflection.RuntimeMethodInfo)(((System.Exception)(ex)).TargetSite)).ReturnType).GenericParameterAttributes' 

threw an exception of type 'System.InvalidOperationException' System.Reflection.GenericParameterAttributes {System.InvalidOperationException}

Message: "Method may only be called on a Type for which Type.IsGenericParameter is true." string

And last but not least the Raw HTTP Request

POST http://localhost:58746/mobile/SendPushV2 HTTP/1.1
Host: localhost:58746
Connection: keep-alive
Content-Length: 140
Accept: */*
Origin: http://localhost:58746
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:58746/Mobile
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: .Admin=3B704FD9ECC241F670F57DA43341FBE8A68BDD64F0E863363F31FF75F676EB8AC78D978DE8F1672D34D5C775B49A42E0F6E0F2FB8F867F9F963B0C0AC6C0F1EDD169AB171B8EE0B6A9ACFCBEF1491AAC8FF623DC9874D514EAE7FCF3407C582EBFE0EF4C4A7D495DF38D8F155A2C6275A884BD0F10CFBF6E4B2232641394E9992999755E9F7CD268747DCD7C81A2062DC8D290E99F0A97E0D6594986936DA9BD643D3814EF3621A671103F55EF85E8B648D68E778D1E21D65C22528CE44A3E980A0C2E8BD35B840189A6D9F11B363E69A310A20A7B554FB2C6BFEB7D81784C273DD1DFDBFF2D0FD91A41B522128C1C5156F22FB84007375682013F08372C580A7A2E85C0; ASP.NET_SessionId=nsmooq2pwg04ursg4aly25bs; .AppRoles=bJt49nUK2-dUVVz5AZH2QrG0VHUGrCXpD6FJ3KU4Q5EI9LbvSP1eUCza3g_3dfdkXqgdHJ19C5xVVWO5oByXPFXL5ateafVmbEH9FX5C10pQsOPrGXEe4DZTVzhFd464zydJG5OMCHvO_sTaRFTRAlX5OfyxG6K8J1yL00FnejVZElH51Zm55zhEjbHnkDlxursOZ55skBu9KmxFWe0tgU-9ieuQIo1TUOHe4sTUQec0LyPPaWd7c_cGFjbHqyzoTcVyBf2v86isy5dXaQmIptstKfl8yE6EU1WzVZ15I-N8J3vJKT_ojRKhrDyGyibkb4S0STvGuaqmGAUE27uaBhkafJVkgvP-yU-GA_TMSffq7DWOzezzPldc5LdpxEymFAjeyuzqSc-OVN0cw1uGXm60xgtFnQSUkXMpCFXgYvcUGNb1757gGcTen-zOyBx5KR8-TNE-Z39J3tpljwax_nUDElogSzaQ_9gR5-59ds1KW_LUsQ-quKA1pFqp8SQv-_F_kzRQvIjLsFozGuwkWybvhMpQvg81uPuZsHEIiOEnajIk0

message=Test%5Cn+%5Cn0n77ap&token=0d14611b5ea03c7301bf6aaa0658fb1373192db85c5805aa1058884b9c994839&date=2013-03-19+13%3A41%3A02&platform=ios

If anyone could help shed some light on this issue for me it would be greatly appreciated.

pat8719
  • 1,700
  • 1
  • 26
  • 47
  • I've started having a suspiciously similar problem with our production FB photo upload code. The issue has been getting progressively worse over the past few weeks. Have you found a solution? Here's my fb bug report: https://developers.facebook.com/bugs/438368212913456 – mellodev Apr 01 '13 at 22:57
  • I added a timeout to the request of 100000, haven't had the problem since but the problem is intermittent so this isn't proof that it is working correctly. – pat8719 Apr 02 '13 at 19:34
  • Thanks for the reply! I've been using a timeout of 25s for a while, but I'll try to increase it. – mellodev Apr 03 '13 at 22:55

1 Answers1

1

One possibility is that you're closing your WebResponse too soon. This code seems suspicious:

using (WebResponse response = request.GetResponse())
{
  return response;
}

This will dispose your response as soon as the method returns. I'd put the using statement in the caller of this method instead.

An alternative when using Parse if you're trying to send a push notification is to write a simple cloud code function that takes the payload and uses Parse's Javascript API to send the push notification. This would allow you to use Parse's .NET SDK to call the cloud function and Parse's Javascript SDK to send the push notification without ever dealing directly with the REST API.

depoll
  • 351
  • 1
  • 2