public async Task HttpConnectionSetsInherentKeepAliveFeature(HttpTransportType transportType, bool expectedValue)
            {
                using (StartVerifiableLog())
                {
                    var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false);

                    testHttpHandler.OnNegotiate((_, cancellationToken) => ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent()));

                    testHttpHandler.OnRequest((request, next, token) => Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)));

                    await WithConnectionAsync(
                        CreateConnection(testHttpHandler, transportType : transportType, loggerFactory : LoggerFactory),
                        async (connection) =>
                    {
                        await connection.StartAsync().OrTimeout();

                        var feature = connection.Features.Get <IConnectionInherentKeepAliveFeature>();
                        Assert.NotNull(feature);
                        Assert.Equal(expectedValue, feature.HasInherentKeepAlive);
                    });
                }
            }
Exemplo n.º 2
0
        public async Task HttpRequestAndErrorResponseLogged()
        {
            var testHttpHandler = new TestHttpMessageHandler(false);

            testHttpHandler.OnNegotiate((request, cancellationToken) => ResponseUtils.CreateResponse(HttpStatusCode.BadGateway));

            var httpOptions = new HttpConnectionOptions();

            httpOptions.Url = new Uri("http://fakeuri.org/");
            httpOptions.HttpMessageHandlerFactory = inner => testHttpHandler;

            const string loggerName = "Microsoft.AspNetCore.Http.Connections.Client.Internal.LoggingHttpMessageHandler";
            var          testSink   = new TestSink();
            var          logger     = new TestLogger(loggerName, testSink, true);

            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory
            .Setup(m => m.CreateLogger(It.IsAny <string>()))
            .Returns((string categoryName) => (categoryName == loggerName) ? (ILogger)logger : NullLogger.Instance);

            try
            {
                await WithConnectionAsync(
                    CreateConnection(httpOptions, loggerFactory : mockLoggerFactory.Object),
                    async (connection) =>
                {
                    await connection.StartAsync(TransferFormat.Text).OrTimeout();
                });
            }
            catch
            {
                // ignore connection error
            }

            Assert.Equal(2, testSink.Writes.Count);
            Assert.Equal("SendingHttpRequest", testSink.Writes[0].EventId.Name);
            Assert.Equal("UnsuccessfulHttpResponse", testSink.Writes[1].EventId.Name);
        }
            public async Task CorrectlyHandlesQueryStringWhenAppendingNegotiateToUrl(string requestedUrl, string expectedNegotiate)
            {
                var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false);

                var negotiateUrlTcs = new TaskCompletionSource <string>();

                testHttpHandler.OnLongPoll(cancellationToken => ResponseUtils.CreateResponse(HttpStatusCode.NoContent));
                testHttpHandler.OnNegotiate((request, cancellationToken) =>
                {
                    negotiateUrlTcs.TrySetResult(request.RequestUri.ToString());
                    return(ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                        ResponseUtils.CreateNegotiationContent()));
                });

                await WithConnectionAsync(
                    CreateConnection(testHttpHandler, url : requestedUrl),
                    async (connection, closed) =>
                {
                    await connection.StartAsync(TransferFormat.Text).OrTimeout();
                });

                Assert.Equal(expectedNegotiate, await negotiateUrlTcs.Task.OrTimeout());
            }
            public async Task HttpConnectionSetsRequestedWithOnAllRequests(HttpTransportType transportType)
            {
                var testHttpHandler  = new TestHttpMessageHandler(autoNegotiate: false);
                var requestsExecuted = false;

                testHttpHandler.OnNegotiate((_, cancellationToken) =>
                {
                    return(ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent()));
                });

                testHttpHandler.OnRequest(async(request, next, token) =>
                {
                    var requestedWithHeader = request.Headers.GetValues(HeaderNames.XRequestedWith);
                    var requestedWithValue  = Assert.Single(requestedWithHeader);
                    Assert.Equal("XMLHttpRequest", requestedWithValue);

                    requestsExecuted = true;

                    return(await next());
                });

                testHttpHandler.OnRequest((request, next, token) =>
                {
                    return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)));
                });

                await WithConnectionAsync(
                    CreateConnection(testHttpHandler, transportType : transportType),
                    async (connection) =>
                {
                    await connection.StartAsync().DefaultTimeout();
                    await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello World"));
                });

                // Fail safe in case the code is modified and some requests don't execute as a result
                Assert.True(requestsExecuted);
            }
            public async Task NegotiateThatReturnsRedirectUrlForeverThrowsAfter100Tries()
            {
                var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false);

                testHttpHandler.OnNegotiate((request, cancellationToken) =>
                {
                    return(ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                        JsonConvert.SerializeObject(new
                    {
                        url = "https://another.domain.url/chat"
                    })));
                });

                using (var noErrorScope = new VerifyNoErrorsScope())
                {
                    await WithConnectionAsync(
                        CreateConnection(testHttpHandler, loggerFactory : noErrorScope.LoggerFactory),
                        async (connection) =>
                    {
                        var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => connection.StartAsync().DefaultTimeout());
                        Assert.Equal("Negotiate redirection limit exceeded.", exception.Message);
                    });
                }
            }
            public async Task NegotiateCanHaveNewFields()
            {
                string connectionId = null;

                var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false);

                testHttpHandler.OnNegotiate((request, cancellationToken) => ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                                                                         JsonConvert.SerializeObject(new
                {
                    connectionId        = "0rge0d00-0040-0030-0r00-000q00r00e00",
                    availableTransports = new object[]
                    {
                        new
                        {
                            transport       = "LongPolling",
                            transferFormats = new[] { "Text" }
                        },
                    },
                    newField = "ignore this",
                })));
                testHttpHandler.OnLongPoll(cancellationToken => ResponseUtils.CreateResponse(HttpStatusCode.NoContent));
                testHttpHandler.OnLongPollDelete((token) => ResponseUtils.CreateResponse(HttpStatusCode.Accepted));

                using (var noErrorScope = new VerifyNoErrorsScope())
                {
                    await WithConnectionAsync(
                        CreateConnection(testHttpHandler, loggerFactory : noErrorScope.LoggerFactory),
                        async (connection) =>
                    {
                        await connection.StartAsync().DefaultTimeout();
                        connectionId = connection.ConnectionId;
                    });
                }

                Assert.Equal("0rge0d00-0040-0030-0r00-000q00r00e00", connectionId);
            }
            public async Task LongPollingTransportCanBeCanceled()
            {
                using (StartVerifiableLog())
                {
                    var cts = new CancellationTokenSource();

                    var httpHandler = new TestHttpMessageHandler(autoNegotiate: false);
                    httpHandler.OnNegotiate((request, cancellationToken) =>
                    {
                        // Cancel token so that the first request poll will throw
                        cts.Cancel();
                        return(ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent()));
                    });

                    var lp = new LongPollingTransport(new HttpClient(httpHandler));

                    await WithConnectionAsync(
                        CreateConnection(httpHandler, transport : lp, transportType : HttpTransportType.LongPolling),
                        async (connection) =>
                    {
                        var ex = await Assert.ThrowsAsync <AggregateException>(async() => await connection.StartAsync(cts.Token).OrTimeout());
                    });
                }
            }
            public async Task NegotiateThatReturnsRedirectUrlDoesNotAddAnotherNegotiateVersionQueryString()
            {
                var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false);
                var negotiateCount  = 0;

                testHttpHandler.OnNegotiate((request, cancellationToken) =>
                {
                    negotiateCount++;
                    if (negotiateCount == 1)
                    {
                        return(ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                            JsonConvert.SerializeObject(new
                        {
                            url = "https://another.domain.url/chat?negotiateVersion=1"
                        })));
                    }
                    else
                    {
                        return(ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                            JsonConvert.SerializeObject(new
                        {
                            connectionId = "0rge0d00-0040-0030-0r00-000q00r00e00",
                            availableTransports = new object[]
                            {
                                new
                                {
                                    transport = "LongPolling",
                                    transferFormats = new[] { "Text" }
                                },
                            }
                        })));
                    }
                });

                testHttpHandler.OnLongPoll((token) =>
                {
                    var tcs = new TaskCompletionSource <HttpResponseMessage>(TaskCreationOptions.RunContinuationsAsynchronously);

                    token.Register(() => tcs.TrySetResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)));

                    return(tcs.Task);
                });

                testHttpHandler.OnLongPollDelete((token) => ResponseUtils.CreateResponse(HttpStatusCode.Accepted));

                using (var noErrorScope = new VerifyNoErrorsScope())
                {
                    await WithConnectionAsync(
                        CreateConnection(testHttpHandler, loggerFactory : noErrorScope.LoggerFactory),
                        async (connection) =>
                    {
                        await connection.StartAsync().DefaultTimeout();
                    });
                }

                Assert.Equal("http://fakeuri.org/negotiate?negotiateVersion=1", testHttpHandler.ReceivedRequests[0].RequestUri.ToString());
                Assert.Equal("https://another.domain.url/chat/negotiate?negotiateVersion=1", testHttpHandler.ReceivedRequests[1].RequestUri.ToString());
                Assert.Equal("https://another.domain.url/chat?negotiateVersion=1&id=0rge0d00-0040-0030-0r00-000q00r00e00", testHttpHandler.ReceivedRequests[2].RequestUri.ToString());
                Assert.Equal("https://another.domain.url/chat?negotiateVersion=1&id=0rge0d00-0040-0030-0r00-000q00r00e00", testHttpHandler.ReceivedRequests[3].RequestUri.ToString());
                Assert.Equal(5, testHttpHandler.ReceivedRequests.Count);
            }
            public async Task NegotiateThatReturnsUrlGetFollowedWithAccessToken()
            {
                var testHttpHandler = new TestHttpMessageHandler(autoNegotiate: false);
                var firstNegotiate  = true;

                testHttpHandler.OnNegotiate((request, cancellationToken) =>
                {
                    if (firstNegotiate)
                    {
                        firstNegotiate = false;

                        // The first negotiate requires an access token
                        if (request.Headers.Authorization?.Parameter != "firstSecret")
                        {
                            return(ResponseUtils.CreateResponse(HttpStatusCode.Unauthorized));
                        }

                        return(ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                            JsonConvert.SerializeObject(new
                        {
                            url = "https://another.domain.url/chat",
                            accessToken = "secondSecret"
                        })));
                    }

                    // All other requests require an access token
                    if (request.Headers.Authorization?.Parameter != "secondSecret")
                    {
                        return(ResponseUtils.CreateResponse(HttpStatusCode.Unauthorized));
                    }

                    return(ResponseUtils.CreateResponse(HttpStatusCode.OK,
                                                        JsonConvert.SerializeObject(new
                    {
                        connectionId = "0rge0d00-0040-0030-0r00-000q00r00e00",
                        availableTransports = new object[]
                        {
                            new
                            {
                                transport = "LongPolling",
                                transferFormats = new[] { "Text" }
                            },
                        }
                    })));
                });

                testHttpHandler.OnLongPoll((request, token) =>
                {
                    // All other requests require an access token
                    if (request.Headers.Authorization?.Parameter != "secondSecret")
                    {
                        return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.Unauthorized)));
                    }
                    var tcs = new TaskCompletionSource <HttpResponseMessage>(TaskCreationOptions.RunContinuationsAsynchronously);

                    token.Register(() => tcs.TrySetResult(ResponseUtils.CreateResponse(HttpStatusCode.NoContent)));

                    return(tcs.Task);
                });

                testHttpHandler.OnLongPollDelete((token) => ResponseUtils.CreateResponse(HttpStatusCode.Accepted));

                Task <string> AccessTokenProvider() => Task.FromResult <string>("firstSecret");

                using (var noErrorScope = new VerifyNoErrorsScope())
                {
                    await WithConnectionAsync(
                        CreateConnection(testHttpHandler, loggerFactory : noErrorScope.LoggerFactory, accessTokenProvider : AccessTokenProvider),
                        async (connection) =>
                    {
                        await connection.StartAsync().DefaultTimeout();
                    });
                }

                Assert.Equal("http://fakeuri.org/negotiate?negotiateVersion=1", testHttpHandler.ReceivedRequests[0].RequestUri.ToString());
                Assert.Equal("https://another.domain.url/chat/negotiate?negotiateVersion=1", testHttpHandler.ReceivedRequests[1].RequestUri.ToString());
                Assert.Equal("https://another.domain.url/chat?id=0rge0d00-0040-0030-0r00-000q00r00e00", testHttpHandler.ReceivedRequests[2].RequestUri.ToString());
                Assert.Equal("https://another.domain.url/chat?id=0rge0d00-0040-0030-0r00-000q00r00e00", testHttpHandler.ReceivedRequests[3].RequestUri.ToString());
                // Delete request
                Assert.Equal(5, testHttpHandler.ReceivedRequests.Count);
            }