【问题标题】:RequireHttpsAttribute with ASP.NET Core MVC - ERR_TOO_MANY_REDIRECTSRequireHttpsAttribute 与 ASP.NET Core MVC - ERR_TOO_MANY_REDIRECTS
【发布时间】:2018-08-22 08:15:20
【问题描述】:

我在 IIS Windows 2016 服务器上有一个简单的 ASP.NET Core 2.0 MVC 网站。

在我的startup.cs 文件中,如果用户在 http 上,我尝试配置自动重定向到 https。 但是,Chrome(以及其他浏览器)一直告诉我:

This page isn’t working
www.example.org redirected you too many times.
Try clearing your cookies. (yup, did that)
ERR_TOO_MANY_REDIRECTS
  1. 我按照本指南强制执行 https: https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl
  2. 我已正确安装 SSL 证书。来自letsencrypt.org
  3. 我已按照本指南使用 IIS 而不是 Kestrel: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?tabs=aspnetcore2x

这是我的代码:

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

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

如果我关闭RequireHttpsAttribute,我可以毫无问题地浏览网站。 我查看了https://stackoverflow.com/a/38019631/560784,上面写着在startup.cs 中包含以下内容。也没有用:(

  services.Configure<ForwardedHeadersOptions>(options =>
  {
       options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
   });

希望得到一些帮助 - 我错过了什么?

【问题讨论】:

  • 这是我第一次看到 app.UseRewriter(options); 在 ASP.NET Core 中强制执行 HTTPS。根据我的经验,像在ConfigureServices 中那样只使用RequireHttpsAttribute 就足够了
  • 感谢您的回复。根据我发布的第一个链接,RequireHttpsAttribute 忽略所有 http 流量请求,这就是为什么(据我所知)app.UseRewriter(options); 稍后需要,这确保重定向 http 流量到 https。但也许我错了?
  • 从第一个链接开始:“RequireHttpsAttribute使用HTTP状态码将浏览器从HTTP重定向到HTTPS”
  • 来自该链接上的 mod (Nbarbettini) “过滤器和重定向做不同的事情:过滤器阻止 ASP.NET Core 响应 HTTP 请求(因此 RequireHttpsAttribute)。重定向将自动重写任何带有 http 到 https 的传入请求。” - 我删除了app.UseRewriter(option) 看看会发生什么,问题仍然存在。挠头。
  • 过滤器和重写器实际上做同样的事情,但它们适用于不同的层。该过滤器仅适用于 mvc,其中重写器适用于在管道中到达该位置的所有请求。如果你有重写器,那么你不需要过滤器。

标签: c# asp.net redirect asp.net-core url-rewriting


【解决方案1】:

根据微软人员对微软文档Enforce HTTPS in an ASP.NET Core 线程的评论:

“如果您使用的是 2.1 之前创建的模板,则需要将 [AllowAnonymous] 应用于登录”

【讨论】:

  • 我还没有时间深入研究这个,但我没有使用登录功能,所以我认为这不是罪魁祸首。
猜你喜欢
  • 2018-10-06
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 2017-01-05
  • 2018-06-15
  • 2017-03-28
相关资源
最近更新 更多