如何在ASP.NET Core中测试https重定向?

时间:2018-09-21 19:02:11

标签: c# unit-testing asp.net-core dotnet-httpclient asp.net-core-2.1

最近,我想出了单元测试来检查我的ASP.NET Core 2.1应用程序的一些重定向规则:

[Fact(DisplayName = "lowercase path")]
public async Task LowercaseRedirect()
{
    var result = await this.Client.GetAsync("/BLOG/");
    Assert.EndsWith("/blog/", result.RequestMessage.RequestUri.PathAndQuery, StringComparison.InvariantCulture);
}

[Fact(DisplayName = "add missing slash")]
public async Task SlashRedirect()
{
    var result = await this.Client.GetAsync("/blog");
    Assert.EndsWith("/blog/", result.RequestMessage.RequestUri.PathAndQuery, StringComparison.InvariantCulture);
}

仅供参考:我目前正在将WebApplicationFactory<TEntryPoint>注入到我的测试类中,该类用于创建HttpClient

但是现在我很好奇如何检查https重定向是否有效。任何想法如何做到这一点?在此先感谢:)

1 个答案:

答案 0 :(得分:3)

对于UseHttpsRedirection,中间件必须具有可用的端口才能重定向到HTTPS。如果没有可用端口,则不会重定向到HTTPS。

可以通过以下任意设置指定HTTPS端口:

  • HttpsRedirectionOptions.HttpsPort
  • ASPNETCORE_HTTPS_PORT环境变量。
  • 开发中,launchsettings.json中的HTTPS网址。
  • 直接在Kestrel或HttpSys上配置的HTTPS URL。

参考:UseHttpsRedirection

要测试UseHttpsRedirection,请指定https端口。您可以按照以下步骤操作:

  1. 使用WebApplicationFactory配置https_port

            public class UnitTest1 : IClassFixture<WebApplicationFactory<CoreHttps.Startup>>
    {
            private readonly WebApplicationFactory<CoreHttps.Startup> _factory;
    
    public UnitTest1(WebApplicationFactory<CoreHttps.Startup> factory)
    {
        _factory = factory.WithWebHostBuilder(builder => builder
            .UseStartup<Startup>()
            .UseSetting("https_port", "8080")); 
    }
    
  2. 默认情况下,请求url为http://localhost/,如果客户端未自动重定向,请检查请求url。

        [Theory]
    [InlineData("/Home")]
    public async Task HttpsRedirectionWithoutAutoRedirect(string url)
    {
        // Arrange
        var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
                                {
                                    AllowAutoRedirect = false
                                });
        // Act
        var response = await client.GetAsync(url);
        // Assert
        Assert.Equal(HttpStatusCode.RedirectKeepVerb, response.StatusCode);
        Assert.StartsWith("http://localhost/",
            response.RequestMessage.RequestUri.AbsoluteUri);
    
        Assert.StartsWith("https://localhost:8080/",
            response.Headers.Location.OriginalString);
    }
    
  3. 如果请求是自动重定向的,请检查请求url。

        [Theory]
    [InlineData("/Home")]
    public async Task HttpsRedirectionWithAutoRedirect(string url)
    {
        // Arrange
        var client = _factory.CreateClient();
        // Act
        var response = await client.GetAsync(url);
    
        // Assert
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.StartsWith("https://localhost:8080/",
            response.RequestMessage.RequestUri.AbsoluteUri);
    }