我在Linux虚拟机中的开源
Caprover
Paas中托管一个ASP.NET Core Docker网络应用程序,它运行良好。使用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>
<div class="alert alert-warning"><strong>HTTP:</strong> Your connection is NOT secure</div>
它总是显示
Caprover使用Docker容器和Nginx代理服务器,所以我怀疑这就是问题所在,因为在我的windows笔记本电脑上运行应用程序时,Request.IsHttps
返回真。
这是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代理服务器处理了https连接的加密/解密,但当把请求转发给容器时,它使用的是普通的http。因此,asp.net从来没有看到https连接,因为它是在代理服务器上终止的。解决办法是转发
和
头。请看下面的修改。
X-Forwarded-For
X-Forwarded-Proto
程序.cs