asp.net-mvc MVC RequireHttps 整个站点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3285014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:23:34  来源:igfitidea点击:

MVC RequireHttps entire site

asp.net-mvcssl

提问by CodeGrue

I have read the previous posts about using the RequireHttpsAttribute to secure individual controllers:

我已经阅读了之前关于使用 RequireHttpsAttribute 保护单个控制器的帖子:

ASP.NET MVC RequireHttps in Production Only

ASP.NET MVC RequireHttps 仅在生产中

but is there a way to apply this to the entire site? Due to my host (discountasp.net) I cannot use the "RequireSSL IIS" setting.

但是有没有办法将它应用到整个站点?由于我的主机 (discountasp.net),我无法使用“RequireSSL IIS”设置。

采纳答案by CodeGrue

I ended up using IIS URL Rewrite 2.0to force the site to switch to HTTPS. This code in web.config does the trick:

我最终使用 IIS URL Rewrite 2.0强制站点切换到 HTTPS。web.config 中的这段代码可以解决问题:

  <system.webServer>
    <!-- This uses URL Rewrite 2.0 to force the entire site into SSL mode -->
    <rewrite xdt:Transform="Insert">
      <rules>
        <rule name="Force HTTPS" enabled="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{HTTPS}" pattern="off" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

回答by hwiechers

Register the RequireHttpsAttributeas a global filter.

将 注册RequireHttpsAttribute为全局过滤器。

In global.asax:

在 global.asax 中:

protected void Application_Start()
{
    GlobalFilters.Filters.Add(new RequireHttpsAttribute());

    //... other stuff
}

回答by Todd Smith

You could always add a check at the application level in your global.asax

您始终可以在 global.asax 中的应用程序级别添加检查

protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (!HttpContext.Current.Request.IsSecureConnection)
   {
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
                                 + HttpContext.Current.Request.RawUrl);
   }
}

回答by Alex Stephens

Just to bring this answer upto date for MVC 3 and aboveuse the following in your Filterconfig.csfile within the App_startfolder

只要把这个答案高达日期为MVC 3及以上使用在以下Filterconfig.cs的内部文件App_start文件夹

        filters.Add(new RequireHttpsAttribute());

Obviously you will need your servers IIS configured to use a valid SSL certificate, cheap certs can be purchased here: https://www.namecheap.com/i think the last time i purchased one it was $9 per domain per year.

显然,您需要将服务器 IIS 配置为使用有效的 SSL 证书,可以在此处购买便宜的证书:https: //www.namecheap.com/我想我上次购买的证书是每个域每年 9 美元。

回答by joegreentea

In your FilterConfig.cs apply this:

在您的 FilterConfig.cs 中应用:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     // only if Debug is not enabled, do not require https for local development
     if (!HttpContext.Current.IsDebuggingEnabled)
          filters.Add(new RequireHttpsAttribute());

     //... any other filters
}

That should force your app to use https on every page.

这应该会强制您的应用程序在每个页面上使用 https。

回答by christo8989

This isn't using RequireHttpsbut I think it's a better solution because it catches the redirect sooner in the MVC Lifecycle.

这没有使用,RequireHttps但我认为这是一个更好的解决方案,因为它在MVC Lifecycle 中更快地捕获重定向。

public class RedirectModule : IHttpModule
{
    private HttpApplication _context;

    public void Init(HttpApplication context)
    {
        _context = context;
        _context.PostResolveRequestCache += HttpRedirect;
    }

    public void HttpRedirect(Object src, EventArgs args)
    {
        if (_context.Request.Url.Scheme == Uri.UriSchemeHttp)
        {
            //Redirect to https
            var scheme = Uri.UriSchemeHttps + "://";
            var authority = _context.Request.Url.Authority;
            var url = _context.Request.RawUrl;

            var redirectTo = scheme + authority + url;
            _context.Response.PermanentRedirect(redirectTo);
        }
    }

    public void Dispose() { }
}

The idea came from this article.

这个想法来自这篇文章

You can register the module in your Web.configor inside the Global.asax. I'll show you in the web.cofig.

您可以Web.configGlobal.asax. 我将在 web.cofig 中向您展示。

<system.webServer>
    <modules>
        <add name="ConfigModuleName" type="Your.Namespace.RedirectModule"/>
    </modules>
</system.webServer>

回答by Nick Niebling

MVC 6 (ASP.NET Core 1.0) works slightly different in it's way of registering filters:

MVC 6 (ASP.NET Core 1.0) 在注册过滤器的方式上略有不同:

Startup.cs - AddMvc with filter for RequireHttpsAttribute:

Startup.cs - AddMvc与过滤器RequireHttpsAttribute

public void ConfigureServices(IServiceCollection services)
{
    // TODO: Register other services

    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(RequireHttpsAttribute));
    });
}

Design decisions explained:

设计决策解释:

  1. Use filter in Startup.csfor global setup (since we want this to apply everywhere). Startup should be responsible for registering and setting up all global rules. If your company employ a new developer, she would expect to find global setup in Startup.cs.
  2. Use RequireHttpsAttributelogic since it's proven (by Microsoft). Never use "magical" strings like "http://" and "https://" when it can be avoided by reusing a Microsoft component created to provide the same logic.
  1. 在 Startup.cs 中使用过滤器进行全局设置(因为我们希望它适用于任何地方)。Startup 应该负责注册和设置所有全局规则。如果您的公司雇用了一位新开发人员,她会希望在 Startup.cs 中找到全局设置。
  2. 使用 RequireHttpsAttribute逻辑,因为它已被证明(由 Microsoft)。如果可以通过重用为提供相同逻辑而创建的 Microsoft 组件来避免这种情况,切勿使用“神奇”字符串,例如“http://”和“https://”。

If you are running your MVC website in localhost without SSL:

如果您在没有 SSL 的 localhost 中运行您的 MVC 网站:

  • http://localhost:1337/ (no SSL)
  • https://localhost:1337/ (SSL)
  • http://localhost:1337/(无 SSL)
  • https://localhost:1337/ (SSL)

Consider looking at how to run without SSL in localhost while still requiring https it in production.

考虑看看如何在 localhost 没有 SSL 的情况下运行,同时在生产中仍然需要 https 它

Note:

笔记:

As an alternative, we could make a "class BaseController : Controller" and make all our controllers inherit from "BaseController" (instead of Controller). Then we only have to set the attribute 1 global place (and don't need to register filter in Startup.cs).

作为替代方案,我们可以创建一个“类 BaseController : Controller”并使我们所有的控制器都继承自“BaseController”(而不是 Controller)。然后我们只需要设置属性1全局位置(不需要在Startup.cs中注册过滤器)。

Some people prefer the attribute style.

有些人更喜欢属性样式。

Example of usage:

用法示例:

[RequireHttpsAttribute]
public class BaseController : Controller
{
    // Maybe you have other shared controller logic..
}

public class HomeController : BaseController
{
    // Add endpoints (GET / POST) for Home controller
}

回答by Dhanuka777

In Global.asax.cs, use "RegisterGlobalFilters" to register global attributes.

在 Global.asax.cs 中,使用“RegisterGlobalFilters”注册全局属性。

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new RequireHttpsAttribute());
    //e.g. filters.Add(new HandleErrorAttribute());
    //e.g. filters.Add(new System.Web.Mvc.AuthorizeAttribute());            
}

回答by DanP

You could use a base class for all of your controllers, and decorate that with the require ssl attribute.

您可以为所有控制器使用基类,并使用 require ssl 属性对其进行装饰。