CodexBloom - Programming Q&A Platform

ASP.NET Core 6: how to to Configure HTTPS Redirection for Kestrel with Custom Certificate

👀 Views: 451 💬 Answers: 1 📅 Created: 2025-07-02
asp.net-core kestrel https C#

I'm working on an ASP.NET Core 6 application and I've encountered an scenario with configuring HTTPS redirection using Kestrel. I've set up a self-signed certificate for local development, but it seems the application is not properly redirecting HTTP requests to HTTPS. I've added the following code in my `Program.cs` file to configure Kestrel: ```csharp var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseKestrel(options => { options.ListenAnyIP(5000); // HTTP options.ListenAnyIP(5001, listenOptions => // HTTPS { listenOptions.UseHttps("path/to/certificate.pfx", "your_certificate_password"); }); }); ``` And I also included the redirection middleware like this: ```csharp builder.Services.AddHttpsRedirection(options => { options.HttpsPort = 5001; }); ``` However, when I try to access `http://localhost:5000`, I just get a `404 Not Found` behavior instead of being redirected to `https://localhost:5001`. I’ve also checked that the certificate is valid by adding it to my local machine's trusted root certification authorities. I tried adding `app.UseHttpsRedirection();` in the request pipeline right after `app.UseRouting();` but that doesn't seem to solve the scenario either. The application runs fine on HTTPS directly, but the redirection is not working as expected. Could there be any specific settings or configurations that I'm missing? I've also checked the logs and there are no errors indicating why the redirection isn't applied. Any help would be appreciated! This is part of a larger application I'm building.