代码之家  ›  专栏  ›  技术社区  ›  CodeGrue

MVC要求整个站点

  •  60
  • CodeGrue  · 技术社区  · 15 年前

    我已经阅读了前面关于使用RequireHttpsAttribute保护各个控制器的文章:

    ASP.NET MVC RequireHttps in Production Only

    但是有没有一种方法可以将这个应用到整个站点?由于我的主机(discountnasp.net),我无法使用“requiressl-iis”设置。

    9 回复  |  直到 8 年前
        1
  •  114
  •   mason Tim Schmelter    9 年前

    注册 RequireHttpsAttribute 作为全局过滤器。

    在Axal.Axax中:

    protected void Application_Start()
    {
        GlobalFilters.Filters.Add(new RequireHttpsAttribute());
    
        //... other stuff
    }
    
        2
  •  22
  •   CodeGrue    15 年前

    我最终使用了IIS URL重写2 强制站点切换到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>
    
        3
  •  18
  •   Bellash    9 年前

    您可以始终在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);
       }
    }
    
        4
  •  13
  •   Alex Stephens    11 年前

    把这个答案更新为 MVC 3及以上 在您的 过滤器配置 文件内 应用程序启动 文件夹

            filters.Add(new RequireHttpsAttribute());
    

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

        5
  •  7
  •   joegreentea    8 年前

    在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
    }
    

    这将迫使你的应用在每一个页面上使用HTTPS。

        6
  •  4
  •   christo8989    9 年前

    这不是用 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() { }
    }
    

    这个想法来自于这个 article .

    您可以在 Web.config 或者里面 Global.asax . 我会在web.cofig中显示。

    <system.webServer>
        <modules>
            <add name="ConfigModuleName" type="Your.Namespace.RedirectModule"/>
        </modules>
    </system.webServer>
    
        7
  •  3
  •   Community Mohan Dere    8 年前

    MVC6(ASP.NET核心1.0)在注册过滤器的方式上工作略有不同:

    startup.cs-带过滤器的addmvc RequireHttpsAttribute :

    public void ConfigureServices(IServiceCollection services)
    {
        // TODO: Register other services
    
        services.AddMvc(options =>
        {
            options.Filters.Add(typeof(RequireHttpsAttribute));
        });
    }
    

    设计决策说明:

    1. 在startup.cs中使用过滤器 对于全局设置(因为我们希望此设置适用于所有地方)。启动应负责注册和设置所有全局规则。如果你的公司雇用了一个新的开发人员,她会期望在startup.cs中找到全局设置。
    2. 使用RequireHttpsAttribute 逻辑,因为它已经被(微软)证明了。如果可以通过重用为提供相同逻辑而创建的Microsoft组件来避免使用“神奇”字符串,如“http://”和“https://”。

    如果您在不使用SSL的本地主机上运行MVC网站:

    • HTTP协议 ://localhost:1337/(无ssl)
    • HTTPS ://localhost:1337/(ssl)

    考虑看看 how to run without SSL in localhost while still requiring https it in production .

    注:

    作为一个 可供替代的 我们可以创建一个“class basecontroller:controller”并使所有的控制器从“basecontroller”(而不是controller)继承。然后我们只需要设置属性1全局位置(并且不需要在startup.cs中注册过滤器)。

    有些人喜欢属性样式。

    使用示例:

    [RequireHttpsAttribute]
    public class BaseController : Controller
    {
        // Maybe you have other shared controller logic..
    }
    
    public class HomeController : BaseController
    {
        // Add endpoints (GET / POST) for Home controller
    }
    
        8
  •  0
  •   Dhanuka777    9 年前

    在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());            
    }
    
        9
  •  -2
  •   DanP    15 年前

    您可以为所有控制器使用一个基类,并用require ssl属性来修饰它。