I have deployed an ASPNET Core 3.1 app on Google's App Engine in a flex environment. The app is still accessible on both HTTP and HTTPS. I want to redirect all HTTP requests to HTTPS. Read in many places that apps on GCP App Engine should be configured on application level to handle http redirection I have tried Microsoft.AspNetCore.Rewrite but it would return too many redirects once the app is deployed on App Engine. When not using the rewriter it will have the app accessible on both protocols. I have even tried a custom middleware as instructed here but again it would return too many redirects. Please tell me where I am wrong and how can I get it resolved. Thanks a lot.
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//app.UseHttpsEnforcement();
//var options = new RewriteOptions().AddRedirectToHttps(301, 443);
//app.UseRewriter(options);
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.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
Custom middleware
public static class AppBuilderExtensions
{
public static IApplicationBuilder UseHttpsEnforcement(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<EnforceHttpsMiddleware>();
}
}
public class EnforceHttpsMiddleware
{
private readonly RequestDelegate _next;
public EnforceHttpsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
HttpRequest req = context.Request;
if (req.IsHttps == false)
{
string url = "https://" + req.Host + req.Path + req.QueryString;
context.Response.Redirect(url, permanent: true);
}
else
{
await _next(context);
}
}
}
app.yaml
runtime: aspnetcore
env: flex
manual_scaling:
instances: 1
resources:
cpu: 1
memory_gb: 1
disk_size_gb: 10
So fortunately I was able to resolve it. The app needed some configuration in order properly able to understand the request. See Natthapol Vanasrivilai's answer here. The solution was targeted at NET Core 2.1 but it turns out to be working in NET Core 3.1 as well.