Ensure ClientHandler properly honors Host header (#1483) Fix #1481

This commit is contained in:
nulltoken 2018-07-06 22:00:25 +02:00 committed by Chris Ross
parent 97c9510a95
commit 3e0b689ac2
2 changed files with 37 additions and 7 deletions

View File

@ -72,10 +72,20 @@ namespace Microsoft.AspNetCore.TestHost
req.Method = request.Method.ToString();
req.Scheme = request.RequestUri.Scheme;
req.Host = HostString.FromUriComponent(request.RequestUri);
if (request.RequestUri.IsDefaultPort)
foreach (var header in request.Headers)
{
req.Host = new HostString(req.Host.Host);
req.Headers.Append(header.Key, header.Value.ToArray());
}
if (req.Host == null || !req.Host.HasValue)
{
// If Host wasn't explicitly set as a header, let's infer it from the Uri
req.Host = HostString.FromUriComponent(request.RequestUri);
if (request.RequestUri.IsDefaultPort)
{
req.Host = new HostString(req.Host.Host);
}
}
req.Path = PathString.FromUriComponent(request.RequestUri);
@ -87,10 +97,6 @@ namespace Microsoft.AspNetCore.TestHost
}
req.QueryString = QueryString.FromUriComponent(request.RequestUri);
foreach (var header in request.Headers)
{
req.Headers.Append(header.Key, header.Value.ToArray());
}
if (requestContent != null)
{
foreach (var header in requestContent.Headers)

View File

@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DiagnosticAdapter;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.TestHost
@ -576,6 +577,29 @@ namespace Microsoft.AspNetCore.TestHost
Assert.NotNull(listener.UnhandledException?.Exception);
}
[Theory]
[InlineData("http://localhost:12345")]
[InlineData("http://localhost:12345/")]
[InlineData("http://localhost:12345/hellohellohello")]
[InlineData("/isthereanybodyinthere?")]
public async Task ManuallySetHostWinsOverInferredHostFromRequestUri(string uri)
{
RequestDelegate appDelegate = ctx =>
ctx.Response.WriteAsync(ctx.Request.Headers[HeaderNames.Host]);
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Host = "otherhost:5678";
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal("otherhost:5678", responseBody);
}
public class TestDiagnosticListener
{
public class OnBeginRequestEventData