.NET 6下ASP.NET Core YARP反向代理HTTP被重定向至HTTPS问题
问题:ASP.NET Core YARP代理开发环境下HTTP请求被强制重定向到HTTPS
我正在开发一个基于YARP的ASP.NET Core反向代理应用(.NET 6),仅作为外部与后端服务的中转。开发时希望localhost同时支持HTTP和HTTPS,但访问http://localhost:5000总会被307内部重定向到HTTPS端点。已经移除了UseHttpsRedirection(),日志显示应用同时监听http://localhost:5000和https://localhost:5001,但重定向问题依然存在。
当前配置如下:
Program.cs
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); var proxyBilder = builder.Services.AddReverseProxy(); proxyBilder.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); var app = builder.Build(); // Configure the HTTP request pipeline. app.MapGet("", () => $"It works! {string.Join(",", app.Urls)}"); app.MapReverseProxy(); app.UseCors(); app.UseAuthorization(); app.MapControllers(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.Run();
launchsettings.json
{ "profiles": { "Vocabulary.ServiceGateaway": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_URLS": "http://+:5000" }, "dotnetRunMessages": true, "useSSL": false } }, "$schema": "https://json.schemastore.org/launchsettings.json" }
解决方案
明确指定双协议监听地址:在
launchsettings.json的ASPNETCORE_URLS中同时声明HTTP和HTTPS地址,替换原有配置为:"ASPNETCORE_URLS": "http://localhost:5000;https://localhost:5001"此配置会让应用同时监听两个端口,避免框架自动添加HTTPS地址引发的冲突。
排查隐藏的HTTPS强制配置:
- 检查
appsettings.json,确保没有启用HttpsRedirection相关配置项; - 确认开发环境下未启用
UseHsts()(当前代码已限定仅非开发环境启用,此部分无需修改)。
- 检查
清理项目缓存:删除项目的
bin和obj目录后重新编译运行,避免旧配置缓存导致的异常。
修改后的launchsettings.json示例
{ "profiles": { "Vocabulary.ServiceGateaway": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_URLS": "http://localhost:5000;https://localhost:5001" }, "dotnetRunMessages": true, "useSSL": false } }, "$schema": "https://json.schemastore.org/launchsettings.json" }
内容的提问来源于stack exchange,提问作者Kingmaker
相关产品推荐
相关产品推荐

