C#如何判断HTTPS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1120190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:40:12  来源:igfitidea点击:

C# How to determine if HTTPS

c#securityhttps

提问by jinsungy

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.

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

采纳答案by Alex

You can write an HttpModulelike this:

你可以这样写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);
        }
    }
}

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

{use SSL}是否使用 SSL 的某个条件在哪里。

EDIT: and, of course, don't forget to add a module definition to a web.config:

编辑:当然,不要忘记向 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>

回答by keithwarren7

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.

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

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

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

回答by Steve Wortham

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

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

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.

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

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

因此,如果您在要进行 SSL 加密的页面上,请像这样调用它:

SetSSL(True)

设置SSL(真)

Otherwise:

除此以外:

SetSSL(False)

设置SSL(假)

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.

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

回答by Steve Wortham

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)

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

回答by Pinch

A bit hard coded but straighforward!

有点硬编码但直截了当!

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

回答by khalid13

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

您还可以在您的 web.configsystem.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>