在 ASP.NET Core 2.1 + IIS 上设置 HTTPS 时遇到问题

Trouble to set HTTPS on ASP.NET Core 2.1 + IIS

我正在尝试将 https 配置到我在 Windows 服务器 2012 上的 IIS 上托管的网站。我的项目是 ASP.NET Core 2.1 的默认 WebApi 应用程序,我正在使用 win-acme 使用 Let's Encrypt 证书配置 IIS。

除了 http 流量没有被重定向到 https 之外,一切都运行良好。如果我检查日志,我得到:

warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
      Failed to determine the https port for redirect.

我认为通过将此添加到我的 ConfigureServices 方法中可以轻松解决此问题:

services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
    options.HttpsPort = 443;
});

但是,现在我根本无法访问我的网站。 Chrome 给我留言:

This page isn't working www.example.com redirected you too many times

如果我检查日志,它会显示一堆这样的行:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://example.com
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 0.1026ms 307
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://example.com
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 0.1837ms 307

有谁知道我做错了什么吗?

我刚找到答案。这可以通过在 ConfigureServices.cs 中添加以下代码来解决:

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardLimit = 2;
    options.KnownProxies.Add(IPAddress.Parse("127.0.10.1"));
    options.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";
});

来源:https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.1#forwarded-headers-middleware-options