HTTPS 在 Caprover 托管的 ASP.NET 核心应用程序中不起作用

HTTPS not working in ASP.NET Core app hosted in Caprover

我在 Linux VM 中的开源 Caprover PaaS 中托管 ASP.NET 核心 Docker Web 应用程序,它运行良好。使用 Caprover 界面,我能够配置该站点的 LetsEncrypt SSL 证书,并且浏览器显示一个挂锁并表示连接是安全的。问题是 ASP.NET 没有检测到应用程序在 Https 模式下是 运行 并且 Request.IsHttps 总是错误的。这是我的测试。

index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

 @if (Request.IsHttps)
{
    <div class="alert alert-success"><strong>HTTPS:</strong> You are using a secure connection</div>
}
else
{
    <div class="alert alert-warning"><strong>HTTP:</strong> Your connection is NOT secure</div>
}

一直显示

Caprover 使用 Docker 容器和 Nginx 代理服务器,所以我怀疑这是问题所在,因为 Request.IsHttps returns 当 运行 我的 windows 上的应用程序时为真笔记本电脑。

这是 program.cs,它只是一个典型的 Visual studio 模板。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

问题是如何配置应用程序以在 Https 中检测它的 运行?

正如所怀疑的那样,问题是 Nginx 代理服务器处理 encryption/decryption 的 https 连接,但是在将请求转发到容器时,它使用纯 http。所以 asp.net 永远不会看到 https 连接,因为它在代理服务器处终止。解决方法是转发X-Forwarded-ForX-Forwarded-Protoheaders。请参阅以下修改。

Program.cs

using Microsoft.AspNetCore.HttpOverrides;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

//ADD: Configure middleware to add X-Forwarded-For and X-Forwarded-Proto headers
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    //accept all networks and proxies
    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
});

var app = builder.Build();

//ADD: use ForwardedHeaders middleware
app.UseForwardedHeaders();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

//REMOVE: not needed as nginx proxy server handling https
//app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

这里是 complete sample on Github.