Peter
Peter

Reputation: 11890

ASP .NET Core https rewrite does not seem to work

Env: ASP.NET Core 2.0. App gets deployed to IIS on Windows Server 2016.

In my startup.cs, I have the following code:

public void ConfigureServices(IServiceCollection services)
  ...
  services.Configure<MvcOptions>(options => {
      options.Filters.Add(new RequireHttpsAttribute());
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
   ...
   var options = new RewriteOptions().AddRedirectToHttps();
   app.UseRewriter(options);
}

However, when the app is deployed to IIS, I do not see http://xxx getting changed to https://xxx in the browser.

I can directly go to https://xxx and that seems to work. However, the idea is to automatically redirect http requests to https.

What is it that I am missing? Do I need to do something on IIS as well? Regards.

Upvotes: 2

Views: 530

Answers (1)

Ignas
Ignas

Reputation: 4328

From the code snippet you posted looks like app.UseRewriter(options); is the last in the Configure() method. Move app.UseMvc(); to the very bottom of the method, since sort order in the pipeline is very important. I suspect MVC processes your request before the rewrite rule is actually applied.

Also:

  • You might not need RequireHttpsAttribute -- run your code without the filter, the HTTPS redirect should still happen.
  • This might depend on your requirements, however I normally set 301 (permanent) redirect to HTTPS. There is an extension for that AddRedirectToHttpsPermanent().

Upvotes: 2

Related Questions