我在Linux中的开源ASP.NET Paas中托管了一个卡普沃尔 Core应用程序,它运行良好。使用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在我的windows膝上型计算机上运行该应用程序时返回true。
这是program.cs,它只是一个典型的Visual模板。
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中?
发布于 2022-02-22 01:48:34
正如所怀疑的,问题是Nginx代理服务器处理https连接的加密/解密,但是当将请求转发到容器时,它使用普通的http。因此,asp.net从未看到过https连接,因为它是在代理服务器上终止的。解决方案是转发X-Forwarded-For和X-Forwarded-Proto头。见下文修改。
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();这是完整的吉顿样本。
https://stackoverflow.com/questions/71215031
复制相似问题