CodexBloom - Programming Q&A Platform

ASP.NET Core 6: solution with HTTPS Redirection and Custom Middleware Interference

πŸ‘€ Views: 54 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
asp.net-core middleware https C#

I'm integrating two systems and I'm working on a personal project and I'm experiencing an scenario in my ASP.NET Core 6 application where HTTPS redirection isn't functioning as expected. I have a custom middleware that handles some logging and request transformations, but it seems to interfere with the automatic redirection from HTTP to HTTPS. When I try to access my site over HTTP, instead of being redirected to HTTPS, I get a 404 behavior. Here’s the relevant part of my `Startup.cs`: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/behavior"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseMiddleware<MyCustomMiddleware>(); // Custom logging middleware app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } ``` I’ve double-checked that HTTPS redirection is configured properly in the `ConfigureServices` method as well: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddHttpsRedirection(options => { options.HttpsPort = 443; }); } ``` I've ensured that the middleware is registered after `UseRouting` but before `UseEndpoints`, as per best practices. However, I suspect that my middleware is consuming the requests and preventing the redirection from occurring. My custom middleware looks like this: ```csharp public class MyCustomMiddleware { private readonly RequestDelegate _next; public MyCustomMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // Logging or other logic here await _next(context); } } ``` I’ve tried rearranging the order of middleware registration and even temporarily removing my custom middleware but still encounter the same scenario. The server is running on Kestrel, and I have the `UseHsts` middleware configured in non-development environments. Any suggestions on how to resolve this scenario? Is there a specific way to ensure that HTTPS redirection works correctly while still utilizing custom middleware? I'm working on a CLI tool that needs to handle this. How would you solve this? Any feedback is welcome!