ASP.NET 核心服务不会将 http:localhost:<https-port> 重定向到 https 架构



我阅读了 https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-2.2&tabs=visual-studio 的说明,这是我Startup.cs代码(这是样板生成的代码(:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // ...
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            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.UseSpaStaticFiles();
        app.UseMvc(...);
        app.UseSpa(...);
    }
}

我的launchSettings.json

{
  "profiles": {
    "MyProject": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

当我打开http://localhost:5000时,我被重定向到https://localhost:5001。但是,当我打开http://localhost:5001时,我只是收到一个错误页面。我想被重定向到https.我在文档中遗漏了某些内容吗?

简短的回答是,你不能那样做。

当您尝试访问http://localhost:5001时,最终双方试图用不同的"语言"进行通信(服务器需要TLS握手,但反而会得到一些垃圾 - 明文http请求(。 因此,服务器无法重定向您,因为双方都没有建立通信通道。

如果您尝试使用 http 连接到端口 443,某些浏览器足够智能,可以切换到 https,但那是客户端。不可能在同一端口上托管 https 和 http。

相关内容

最新更新