Problem
How to ensure the use of HTTPS in ASP.NET Core.
Solution
Create an empty project and update Startup to add services and middleware for MVC, including the filter for HTTPS,
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddMvc(options =>
- {
- options.Filters.Add(new RequireHttpsAttribute());
- });
- }
-
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseMvcWithDefaultRoute();
- }
You could setup a redirect from HTTP to HTTPS on the web-server (e.g. IIS) or use middleware in ASP.NET Core,
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- var options = new RewriteOptions()
- .AddRedirectToHttps(StatusCodes.Status301MovedPermanently, 44384);
-
- app.UseRewriter(options);
-
- app.UseMvcWithDefaultRoute();
- }
Note
For testing in IIS Express, you can enable SSL from project Properties > Debug tab by checking the Enable SSL flag.
Source Code
GitHub