From f2f1d7751710342d22c55edf83a01615409f2a49 Mon Sep 17 00:00:00 2001 From: huysentruitw Date: Mon, 6 May 2019 17:52:56 +0200 Subject: [PATCH] TestHost.WebSocketClient should set Request.Host (#9973) --- src/Hosting/TestHost/src/WebSocketClient.cs | 6 ++ .../TestHost/test/WebSocketClientTests.cs | 56 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/Hosting/TestHost/test/WebSocketClientTests.cs diff --git a/src/Hosting/TestHost/src/WebSocketClient.cs b/src/Hosting/TestHost/src/WebSocketClient.cs index cec96ab4ce..40a904cc57 100644 --- a/src/Hosting/TestHost/src/WebSocketClient.cs +++ b/src/Hosting/TestHost/src/WebSocketClient.cs @@ -59,6 +59,12 @@ namespace Microsoft.AspNetCore.TestHost scheme = (scheme == "ws") ? "http" : scheme; scheme = (scheme == "wss") ? "https" : scheme; request.Scheme = scheme; + if (!request.Host.HasValue) + { + request.Host = uri.IsDefaultPort + ? new HostString(HostString.FromUriComponent(uri).Host) + : HostString.FromUriComponent(uri); + } request.Path = PathString.FromUriComponent(uri); request.PathBase = PathString.Empty; if (request.Path.StartsWithSegments(_pathBase, out var remainder)) diff --git a/src/Hosting/TestHost/test/WebSocketClientTests.cs b/src/Hosting/TestHost/test/WebSocketClientTests.cs new file mode 100644 index 0000000000..0b7571e211 --- /dev/null +++ b/src/Hosting/TestHost/test/WebSocketClientTests.cs @@ -0,0 +1,56 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Xunit; + +namespace Microsoft.AspNetCore.TestHost.Tests +{ + public class WebSocketClientTests + { + [Theory] + [InlineData("http://localhost/connect", "localhost")] + [InlineData("http://localhost:80/connect", "localhost")] + [InlineData("http://localhost:81/connect", "localhost:81")] + public async Task ConnectAsync_ShouldSetRequestProperties(string requestUri, string expectedHost) + { + HttpRequest capturedRequest = null; + + using (var testServer = new TestServer(new WebHostBuilder() + .Configure(app => + { + app.Run(ctx => + { + if (ctx.Request.Path.StartsWithSegments("/connect")) + { + capturedRequest = ctx.Request; + } + return Task.FromResult(0); + }); + }))) + { + var client = testServer.CreateWebSocketClient(); + + try + { + await client.ConnectAsync( + uri: new Uri(requestUri), + cancellationToken: default(CancellationToken)); + } + catch + { + // An exception will be thrown because our dummy endpoint does not implement a full Web socket server + } + } + + Assert.Equal("http", capturedRequest.Scheme); + Assert.Equal(expectedHost, capturedRequest.Host.Value); + Assert.Equal("/connect", capturedRequest.Path); + } + } +}