C# 如何判断是否是HTTPS

发布于 2024-07-27 00:52:28 字数 68 浏览 2 评论 0原文

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

How do I determine and force users to view my website using HTTPS only? I know it can be done through IIS, but want to know how its done programmatically.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

醉生梦死 2024-08-03 00:52:28

您可以像这样编写 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>

You can write an HttpModule like this:

/// <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);
        }
    }
}

Where {use SSL} is a some condition whether to use SSL or not.

EDIT: and, of course, don't forget to add a module definition to a 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>
冰雪之触 2024-08-03 00:52:28

有点硬编码,但很简单!

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

A bit hard coded but straighforward!

if (!HttpContext.Current.Request.IsSecureConnection)
{
   Response.Redirect("https://www.foo.com/foo/");
}
爺獨霸怡葒院 2024-08-03 00:52:28

您必须将其从 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(True)

否则:

SetSSL(False)

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

You'd have to convert this from VB.NET to C#, but this is what I use in my sites:

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

It's more code than some of the other techniques, but there's a reason for it. This method will only redirect when it's not in the mode it should be in. And when it does do a redirect, it does a 301 (permanent) redirection. The benefit there is that search engines will follow the 301 redirection and that will prevent any possibility of them indexing the same page twice (in http and https mode). You can compare this with the default behavior of Response.Redirect (302 temporary redirect) which Google, for example, doesn't treat the same way. They will not change their index based on a temporary redirect.

So if you're on a page that you want to be SSL-encrypted, call it like this:

SetSSL(True)

Otherwise:

SetSSL(False)

And if you really need this to be globally applied, I'd call SetSSL(True) in the Application_BeginRequest of your global.asax. Beware that SSL will slow things down a bit. For that reason I'm typically very selective when switching between http and https. In fact, out of dozens of sites I've developed there's only been two that use SSL throughout the entire site.

冬天的雪花 2024-08-03 00:52:28

本文介绍将请求移入和移出 SSL。 有时您不希望用户查看 SSL 中的页面,因为它会消耗不需要保护的页面的过程周期。

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

This article covers moving requests in and out of SSL. Sometimes you dont want the user viewing a page in SSL because it burns proc cycles for pages that dont need to be secured.

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

寒冷纷飞旳雪 2024-08-03 00:52:28

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

IIR you can check the request (HttpContext.Current.Request) for the domain which you then can check what protocol is being used (http,https, ftp, etc)

椒妓 2024-08-03 00:52:28

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

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

You can also set up a rewrite rule in your web.config under the system.webServer tag. eg:

   <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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文