Exemplo n.º 1
0
        public IAsyncResult BeginInvoke(Message msg, AsyncCallback callback, object state)
        {
            var    context = WebOperationContext.Current;
            object value;
            Stream s = null;

            if (msg.Properties.TryGetValue("WebBodyFormatMessageProperty", out value))
            {
                var prop = value as WebBodyFormatMessageProperty;
                if (prop != null && (prop.Format == WebContentFormat.Json || prop.Format == WebContentFormat.Raw))
                {
                    s = StreamMessageHelper.GetStream(msg);
                }
            }
            else
            {
                var ms = new MemoryStream();
                using (var xw = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
                {
                    msg.WriteBodyContents(xw);
                }
                ms.Seek(0, SeekOrigin.Begin);
                s = ms;
            }
            return(DispatchToHttpServer(context.IncomingRequest, s, context.OutgoingResponse, _config.BufferRequestContent, callback, state));
        }
        public async Task <Message> InvokeAsync(Message msg)
        {
            var    context = WebOperationContext.Current;
            object value;
            Stream s = null;

            if (msg.Properties.TryGetValue("WebBodyFormatMessageProperty", out value))
            {
                var prop = value as WebBodyFormatMessageProperty;
                if (prop != null && (prop.Format == WebContentFormat.Json || prop.Format == WebContentFormat.Raw))
                {
                    s = StreamMessageHelper.GetStream(msg);
                }
            }
            else
            {
                var ms = new MemoryStream();
                using (var xw = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
                {
                    msg.WriteBodyContents(xw);
                }
                ms.Seek(0, SeekOrigin.Begin);
                s = ms;
            }
            var request  = MakeHttpRequestMessageFrom(context.IncomingRequest, s, _config.BufferRequestContent);
            var response = await _serverInvoker.SendAsync(request, CancellationToken.None);

            CopyHttpResponseMessageToOutgoingResponse(response, context.OutgoingResponse);
            var stream = response.Content != null ? await response.Content.ReadAsStreamAsync() : null;

            return(StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream()));
        }
Exemplo n.º 3
0
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count,
                                                   CancellationToken cancellationToken)
        {
            if (channel.State != CommunicationState.Opened)
            {
                throw new InvalidOperationException();
            }

            await readerSemaphore.WaitAsync(cancellationToken);

            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    if (pendingReaderStream == null)
                    {
                        // local cancellation source dependent on outer token that nukes the channel
                        // on abort. That renders the channel unusable for further operations while a
                        // timeout expiry might not.
                        using (var ct = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
                        {
                            ct.Token.Register(() => channel.Abort());

                            // read from the channel
                            var msg = await Task.Factory.FromAsync(channel.BeginReceive,
                                                                   (Func <IAsyncResult, Message>) channel.EndReceive,
                                                                   TimeSpan.FromMilliseconds(ReadTimeout), null);

                            if (!msg.IsEmpty && msg.Headers.Action != "eof")
                            {
                                pendingReaderStream = StreamMessageHelper.GetStream(msg);
                            }
                        }
                    }
                    if (pendingReaderStream != null)
                    {
                        var bytesRead = await pendingReaderStream.ReadAsync(buffer, offset, count,
                                                                            CancellationTokenSource.CreateLinkedTokenSource(
                                                                                new CancellationTokenSource(TimeSpan.FromMilliseconds(ReadTimeout)).Token,
                                                                                cancellationToken).Token);

                        if (bytesRead == 0)
                        {
                            pendingReaderStream = null;
                            continue;
                        }
                        return(bytesRead);
                    }
                    return(0);
                }
                throw new OperationCanceledException(cancellationToken);
            }
            finally
            {
                readerSemaphore.Release();
            }
        }
        public async Task <Message> InvokeAsync(Message msg)
        {
            var    webOperContext = WebOperationContext.Current;
            object value;
            Stream s = null;

            if (msg.Properties.TryGetValue("WebBodyFormatMessageProperty", out value))
            {
                var prop = value as WebBodyFormatMessageProperty;
                if (prop != null && (prop.Format == WebContentFormat.Json || prop.Format == WebContentFormat.Raw))
                {
                    s = StreamMessageHelper.GetStream(msg);
                }
            }
            else
            {
                var ms = new MemoryStream();
                using (var xw = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
                {
                    msg.WriteBodyContents(xw);
                }
                ms.Seek(0, SeekOrigin.Begin);
                s = ms;
            }

            var outputStream             = new MemoryStream();
            var onSendingHeadersHandlers = new List <Tuple <Action <object>, object> >();
            var owinContext = MakeOwinContextFrom(webOperContext.IncomingRequest, s, outputStream, onSendingHeadersHandlers);
            await _next.Invoke(owinContext.Environment);

            onSendingHeadersHandlers.Reverse();
            foreach (var t in onSendingHeadersHandlers)
            {
                t.Item1(t.Item2);
            }
            outputStream.Seek(0, SeekOrigin.Begin);
            CopyOwinContextToOutgoingResponse(owinContext, webOperContext.OutgoingResponse);
            return(StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", outputStream));
        }
        private HttpRequestMessage BuildForwardedRequest(WebOperationContext context, Message msg)
        {
            var incomingRequest = context.IncomingRequest;

            var mappedUri  = new Uri(incomingRequest.UriTemplateMatch.RequestUri.ToString().Replace(_config.RelayAddress.ToString(), _config.TargetAddress.ToString()));
            var newRequest = new HttpRequestMessage(new HttpMethod(incomingRequest.Method), mappedUri);

            // Copy headers
            var hostHeader = _config.TargetAddress.Host + (_config.TargetAddress.Port != 80 || _config.TargetAddress.Port != 443 ? ":" + _config.TargetAddress.Port : "");

            foreach (var name in incomingRequest.Headers.AllKeys.Where(name => !_httpContentHeaders.Contains(name)))
            {
                newRequest.Headers.TryAddWithoutValidation(name, name == "Host" ? hostHeader : incomingRequest.Headers.Get(name));
            }

            if (msg != null)
            {
                Stream messageStream = null;
                if (msg.Properties.TryGetValue("WebBodyFormatMessageProperty", out var value))
                {
                    if (value is WebBodyFormatMessageProperty prop && (prop.Format == WebContentFormat.Json || prop.Format == WebContentFormat.Raw))
                    {
                        messageStream = StreamMessageHelper.GetStream(msg);
                    }
                }
                else
                {
                    var ms = new MemoryStream();
                    using (var xw = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
                    {
                        msg.WriteBodyContents(xw);
                    }

                    ms.Seek(0, SeekOrigin.Begin);
                    messageStream = ms;
                }

                if (messageStream != null)
                {
                    if (_config.BufferRequestContent)
                    {
                        var ms1 = new MemoryStream();
                        messageStream.CopyTo(ms1);
                        ms1.Seek(0, SeekOrigin.Begin);
                        newRequest.Content = new StreamContent(ms1);
                    }
                    else
                    {
                        var ms1 = new MemoryStream();
                        messageStream.CopyTo(ms1);
                        ms1.Seek(0, SeekOrigin.Begin);

                        var debugMs = new MemoryStream();
                        ms1.CopyTo(debugMs);
                        debugMs.Seek(0, SeekOrigin.Begin);

                        var result = Encoding.UTF8.GetString(debugMs.ToArray());
                        WriteJsonObject(result);

                        ms1.Seek(0, SeekOrigin.Begin);
                        newRequest.Content = new StreamContent(ms1);
                    }

                    foreach (var name in incomingRequest.Headers.AllKeys.Where(name => _httpContentHeaders.Contains(name)))
                    {
                        newRequest.Content.Headers.TryAddWithoutValidation(name, incomingRequest.Headers.Get(name));
                    }
                }
            }

            return(newRequest);
        }