ASP.NET Core redirect http to https
Edit: While it still works, things changed a bit since I wrote this answer. Please check D.L.MAN's more up to date answer: https://stackoverflow.com/a/56800707/844207
In asp.net Core 2 you can use an URL Rewrite independent of the Web Server, by usingapp.UseRewriter in Startup.Configure, like this:
if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // todo: replace with app.UseHsts(); once the feature will be stable app.UseRewriter(new RewriteOptions().AddRedirectToHttps(StatusCodes.Status301MovedPermanently, 443)); }
Actually (ASP.NET Core 1.1) there is a middleware named Rewrite that includes a rule for what you are trying to do.
You can use it on Startup.cs like this:
var options = new RewriteOptions() .AddRedirectToHttpsPermanent();app.UseRewriter(options);
In ASP.NET Core 2.2 you should use Startup.cs settings for redirect http to https
so add this in ConfigureServices:
public void ConfigureServices(IServiceCollection services){ services.AddHttpsRedirection(options => { options.HttpsPort = 443; }); // <=== Add this (AddHttpsRedirection) ===== services.AddRazorPages(); }
and add this in Configure :
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); // <=== Add this ===== } app.UseHttpsRedirection(); // <=== Add this =====}
in launchSettings.json check blow items exsits:
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:63278", "sslPort": 44377 // <<=== check this port exists. } }, "YOUR_PROJECT_NAME": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": true, "applicationUrl": "https://localhost:5001;http://localhost:5000", // <=== check https url exists. "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } }}
then enjoy it.