繁体   English   中英

C#如何确定HTTPS

[英]C# How to determine if HTTPS

如何确定并强制用户仅使用HTTPS查看我的网站? 我知道它可以通过IIS完成,但想知道它是如何以编程方式完成的。

你可以像这样写一个HttpModule

/// <summary>
/// Used to correct non-secure requests to secure ones.
/// If the website backend requires of SSL use, the whole requests 
/// should be secure.
/// </summary>
public class SecurityModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }

    protected void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = ((HttpApplication)(sender));
        HttpRequest request = application.Request;
        HttpResponse response = application.Response;

        // if the secure connection is required for backend and the current 
        // request doesn't use SSL, redirecting the request to be secure
        if ({use SSL} && !request.IsSecureConnection)
        {
            string absoluteUri = request.Url.AbsoluteUri;
            response.Redirect(absoluteUri.Replace("http://", "https://"), true);
        }
    }
}

其中{use SSL}是否是使用SSL的某种条件。

编辑 :当然,不要忘记将模块定义添加到web.config

<system.web>
    <httpModules>
        <!--Used to redirect all the unsecure connections to the secure ones if necessary-->
        <add name="Security" type="{YourNamespace}.Handlers.SecurityModule, {YourAssembly}" />
        ...
    </httpModules>
</system.web>

有点硬编码但直截了当!

if (!HttpContext.Current.Request.IsSecureConnection)
{
   Response.Redirect("https://www.foo.com/foo/");
}

你必须将它从VB.NET转换为C#,但这是我在我的网站中使用的:

Imports System.Web.HttpContext

Public Shared Sub SetSSL(Optional ByVal bEnable As Boolean = False)
  If bEnable Then
    If Not Current.Request.IsSecureConnection Then
      Dim strHTTPS As String = "https://www.mysite.com"
      Current.Response.Clear()
      Current.Response.Status = "301 Moved Permanently"
      Current.Response.AddHeader("Location", strHTTPS & Current.Request.RawUrl)
      Current.Response.End()
    End If
  Else
    If Current.Request.IsSecureConnection Then
      Dim strHTTP As String = "http://www.mysite.com"
      Current.Response.Clear()
      Current.Response.Status = "301 Moved Permanently"
      Current.Response.AddHeader("Location", strHTTP & Current.Request.RawUrl)
      Current.Response.End()
    End If
  End If
End Sub

它的代码比其他一些技术更多,但这是有原因的。 此方法仅在未处于应该处于的模式时才重定向。当它执行重定向时,它会执行301(永久)重定向。 好处是搜索引擎将遵循301重定向,这将防止他们将同一页面索引两次(在http和https模式下)的任何可能性。 您可以将此与Response.Redirect(302临时重定向)的默认行为进行比较,例如,Google不会采用相同的方式。 他们不会根据临时重定向更改其索引。

因此,如果您在要加密SSL的页面上,请将其命名为:

SetSSL(真)

除此以外:

SetSSL(假)

如果你真的需要全局应用它,我会在你的global.asax的Application_BeginRequest中调用SetSSL(True)。 请注意,SSL会减慢速度。 出于这个原因,我在http和https之间切换时通常非常有选择性。 事实上,在我开发的几十个网站中,只有两个在整个网站上使用SSL。

本文介绍了移入和移出SSL的请求。 有时你不希望用户在SSL中查看页面,因为它会为不需要保护的页面烧掉proc周期。

http://weblogs.asp.net/kwarren/archive/2005/07/08/418541.aspx

IIR您可以检查域的请求(HttpContext.Current.Request),然后您可以检查正在使用的协议(http,https,ftp等)

您还可以在system.webServer标记下的web.config中设置重写规则。 例如:

   <rewrite>
      <rules>
        <rule name="Redirect to HTTPS" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost(:\d+)?$" negate="true" ignoreCase="true" />
            <add input="{HTTP_HOST}" matchType="Pattern" pattern="^127\.0\.0\.1(:\d+)?$" negate="true" />
            <add input="{HTTPS}" pattern="off" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
        </rule>
      </rules>
    </rewrite>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM