首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Caprover托管的ASP.NET核心应用程序中不工作的HTTPS

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

Stack Overflow用户
提问于 2022-02-22 01:48:34
回答 1查看 272关注 0票数 0

我在Linux中的开源ASP.NET Paas中托管了一个卡普沃尔 Core应用程序,它运行良好。使用Caprover接口,我能够配置站点的LetsEncrypt SSL证书,浏览器显示一个挂锁,并表示连接是安全的。问题是,ASP.NET没有检测到应用程序在Https模式下运行,而Request.IsHttps总是错误的。这是我的测试。

index.cshtml

代码语言:javascript
复制
@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模板。

代码语言:javascript
复制
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中?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-22 01:48:34

正如所怀疑的,问题是Nginx代理服务器处理https连接的加密/解密,但是当将请求转发到容器时,它使用普通的http。因此,asp.net从未看到过https连接,因为它是在代理服务器上终止的。解决方案是转发X-Forwarded-ForX-Forwarded-Proto头。见下文修改。

Program.cs

代码语言:javascript
复制
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();

这是完整的吉顿样本

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71215031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档