1

I have made a Web API Service in C# and host it in server which was running good for a while. API Service has the following feature.

  1. Client can send request and get response through "API Controller"
  2. Client can connect to the Socket via Signalr and client will be streamed with data

Recent days, I facing some issue randomly with the API services where there is a sudden disconnection of sockets over a particular period of time. When I see the web api logs, I got the following error.

System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.IO.IOException ---> System.Net.HttpListenerException: An operation was attempted on a nonexistent network connection at System.Net.HttpRequestStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) --- End of inner exception stack trace --- at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) at System.Net.Http.StreamToStreamCopy.StartRead() --- End of inner exception stack trace --- --- End of inner exception stack trace --- at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at ApiServices.Controllers.Streaming.StreamSubs.ListToolbar() ---> (Inner Exception #0) System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.IO.IOException ---> System.Net.HttpListenerException: An operation was attempted on a nonexistent network connection at System.Net.HttpRequestStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) --- End of inner exception stack trace --- at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state) at System.Net.Http.StreamToStreamCopy.StartRead() --- End of inner exception stack trace ---<---

Most of the answers pointing to the client area but for me it seems to be in Api Server

The issue was happening trice in a day and I'm not sure about the root cause. Anyone here familiar with the issue?

On the server, I have following line to read the whole request body, Anything wrong here?

var task = Request.Content.ReadAsStringAsync();

On the class

  [RoutePrefix("api/Stream/{actionType}/{user}")]
  public class StreamSubs : ApiController
  {
     [Route("Justs"), HttpPost]
    public int SubTokens(string user, string actionType)//, [FromBody] List<int> tokens)
    {
      var tokens = ReadRequestContent(user);
      if (tokens == null)
        return -1;
      DoSubs(user, actionType, tokens);
      return 1;
    }

    internal List<int> ReadRequestContent(string user)
    {
      var liststr = "";
      try
      {
        var task = Request.Content.ReadAsStringAsync();
        var delay = Task.Delay(TimeSpan.FromSeconds(Utils.HttpReadRequestContentTimeoutInSeconds));
        var timeoutTask = Task.WhenAny(task, delay);
        if (timeoutTask.Result != task)
        {
          Log.Trace("StreamSub --- {0} --- Read request content timeout", _streamType);
          return null;
        }
        var tstr = task.Result;
        var len = Request.Content.Headers.ContentLength;
        if (len != null && len != tstr.Length)
        {
          Log.Trace("{2} subs length mismatch. HL: {0}, DL: {1}", len, tstr.Length, _streamType);
          return null;
        }

        liststr = tstr;
        if (tstr != null)
        {
          if (tstr.Length > 0)
          {
            if (!tstr.Contains("null"))
            {
              try
              {
                //process the string
              }
              catch (JsonSerializationException jexp1) { }
              catch (JsonReaderException jexp2) { }
              catch
              {
                Log.Error("Exception in ReadRequestContentIndices() - INT- Tokens List - " + liststr);
              }
            }
          }
        }

      }
      catch (Exception e)
      {
        //if (DateTime.Now.TimeOfDay <= System.TimeSpan.Parse("14:30:00"))
        //{
        Log.Error("Exception in ReadRequestContent() - INT - Tokens List - " + liststr);
        //}        
        Log.Error(e);
      }
      return null;
    }
  }
Gopichandar
  • 2,742
  • 2
  • 24
  • 54
  • Show code around `Request.Content.ReadAsStringAsync()` – Backs Dec 18 '19 at 11:12
  • The error indicates there is no route to the server from the client. Either the server is not running or Route and/or RoutePrefix is wrong. – jdweng Dec 18 '19 at 11:30

1 Answers1

0

Have you checked out CSHARP-1160?

It basically says that you need to append ?connect=replicaSet to your connection string.

Effectively, we've made a distinction between connecting to a standalone server and connecting directly to a replica set member, where the latter is relatively uncommon. Unfortunately, MongoLab's Single-Node settings are actually a single node replica set and this causes us to not trust it. You can fix this by appending ?connect=replicaSet to your connection string. It will force the driver to move into replica set mode and all will work.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61