C#如何确定HTTPS

jin*_*ngy 16 c# security https

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

Ale*_*lex 20

你可以这样写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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

{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>
Run Code Online (Sandbox Code Playgroud)


Pin*_*nch 12

有点硬编码但直截了当!

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


Ste*_*ham 5

你必须将它从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
Run Code Online (Sandbox Code Playgroud)

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

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

SetSSL(真)

除此以外:

SetSSL(假)

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