ASP.NET Core将http重定向到https

Hub*_*y03 13 asp.net asp.net-mvc ssl redirect asp.net-core

我在web.config中创建了一个重定向规则,将我的网站从http重定向到https.我遇到的问题是网站上的每个链接现在都是https.我有很多链接到其他网站没有SSL,因此我得到证书错误.这就是我所做的:

  <rewrite>
  <rules>
    <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny">
        <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>
Run Code Online (Sandbox Code Playgroud)

我如何仅为我的域重定向https而不是我的网站上的每个链接?

Ser*_*pez 11

实际上(ASP.NET Core 1.1)有一个名为Rewrite 的中间件,其中包含了您要执行的操作的规则.

您可以在Startup.cs上使用它,如下所示:

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

app.UseRewriter(options);
Run Code Online (Sandbox Code Playgroud)

  • 从Asp .Net Core 2.1开始,请使用“ app.UseHttpsRedirection();”中间件。参考:https://docs.microsoft.com/zh-cn/aspnet/core/security/enforcing-ssl?view=aspnetcore-2.1&amp;tabs=visual-studio (4认同)

vic*_*tan 11

在asp.net Core 2中,可以通过在Startup.Configure中使用app.UseRewriter来使用独立于Web服务器的URL重写,如下所示:

        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));
        }
Run Code Online (Sandbox Code Playgroud)


D.L*_*MAN 8

在ASP.NET Core 2.2中,应使用Startup.cs设置将http重定向到https

因此,将其添加到ConfigureServices中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpsRedirection(options =>
    {
        options.HttpsPort = 443;
    });                           // ===== Add this =====
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到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 =====
}
Run Code Online (Sandbox Code Playgroud)

然后享受它。