C#如何确定HTTPS

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

你可以像这样写一个HttpModule

 ///  /// Used to correct non-secure requests to secure ones. /// If the website backend requires of SSL use, the whole requests /// should be secure. ///  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

     ...   

有点硬编码但直截了当!

 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中设置重写规则。 例如: