代码之家  ›  专栏  ›  技术社区  ›  The Muffin Man

逐页强制SSL(HTTPS)

  •  2
  • The Muffin Man  · 技术社区  · 15 年前

    如何在代码隐藏中设置页面加载事件以重定向到具有https前缀的URL?我需要它来处理附加了查询字符串的URL。

    构建直接指向HTTPS页面的链接是一回事,但我不希望用户能够手动将其更改为HTTP页面。

    另外,我不想用JavaScript来完成它,因为它可能被关闭了。

    我猜是正则表达式?

    5 回复  |  直到 15 年前
        1
  •  2
  •   Aren    15 年前

    我们用一个特殊的属性标记我们的ssl必需页 ForceSslAttribute . 然后我们有一个 HttpModule 这会下拉当前页面的类并检查其属性。

    如果该属性存在于页面上,它将获取传递的确切URL并从中更改协议 http https 然后调用重定向。

    也许有一个简单的方法,但这就是我们的方法。

    属性:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
    public sealed class ForceSslAttribute : Attribute
    {
        // Marker Attribute
    }
    

    页面示例(代码隐藏):

    [ForceSsl]
    public partial class User_Login : Page
    {
        //...
    }
    

    您可以这样计算出页面的类型:

    HttpContext.Current.CurrentHandler.GetType()
    

    所有 Page 实施 IHttpHandler 当你访问一个页面时,它会起作用。

    这个方法最酷的部分是你可以标记任何一个IHttphandler,它也会强制重定向:)

        2
  •  2
  •   tidwall    15 年前

    将此添加到页面顶部加载

    if (Request.ServerVariables["HTTPS"] != "ON")
    {
        Response.Redirect("https://" + Request["HTTP_HOST"] + Request.RawUrl);
    }
    
        3
  •  1
  •   radimd    15 年前

    我在global.asax应用程序\u beginrequest中使用以下内容

    If needsSSL <> Request.IsSecureConnection Then
        If needsSSL Then
            Response.Redirect(Uri.UriSchemeHttps + Uri.SchemeDelimiter + Request.Url.Host +  Request.Url.PathAndQuery, True)
        Else
            Response.Redirect(Uri.UriSchemeHttp + Uri.SchemeDelimiter + Request.Url.Host + Request.Url.PathAndQuery, True)
        End If
    End If
    
        4
  •  0
  •   afzalex    15 年前

    有一个IIS7模块用于 URL rewriting . 非常方便,但是您需要访问IIS,并且需要一些时间来学习如何编写规则。简单的HTTP->HTTPS规则只需几秒钟。

    请小心,因为您添加的任何规则都将存储在web.config中,所以不要删除/重写它,否则您必须重新编写它们。

        5
  •  0
  •   Manik Arora    10 年前

    使用ASP强制SSL 要使用ASP强制SSL,请执行以下步骤:

    Click Start, click Run, type Notepad, and then click OK.
    Paste the following code into a blank Notepad document. On the File menu, click Save As, and then save the following code in the root of your Web server as an include file named ForceSSL.inc:
    
    <%
       If Request.ServerVariables("SERVER_PORT")=80 Then
          Dim strSecureURL
          strSecureURL = "https://"
          strSecureURL = strSecureURL & Request.ServerVariables("SERVER_NAME")
          strSecureURL = strSecureURL & Request.ServerVariables("URL")
          Response.Redirect strSecureURL
       End If
    %>
    
    
    For each page that requires SSL, paste the following code at the top of the page to reference the include file from the previous step:
    
    <%@Language="VBSCRIPT"%>
    <!--#include virtual="/ForceSSL.inc"-->
    
    
    When each page is browsed, the ASP code that is contained in the include file detects the port to determine if HTTP is used. If HTTP is used, the browser will be redirected to the same page by using HTTPS.