ASP.NET Core 使用 URL Rewrite 中间件实现 HTTP 重定向到 HTTPS

在传统 ASP.NET 程序中,我们可以通过配置 IIS 的“URL 重写”功能实现将 HTTP 请求重定向为 HTTPS 。但是该方法在 ASP.NET Core 应用中不再工作。在 ASP.NET Core 应用中,我们可以通过一个名为 URL Rewriting 的中间件实现该功能。 首先,请确保项目已经引用了 Microsoft.AspNetCore.Rewrite 包,如果没有,可以通过 nuget 管理器添加引用。接下来只需要在 Startup.cs 文件的 Configure 方法中加入以下代码即可:

var options = new RewriteOptions()
    .AddRedirectToHttpsPermanent();

app.UseRewriter(options);

Notice:以上代码来自 Microsoft.AspNetCore.Rewrite 命名空间。