强制ASP.NET Web应用程序使用SSL

If your ASP.NET application requires SSL, then you should make sure that user uses

如果您的ASP.NET应用程序需要SSL,则应确保该用户使用

https: instead of https而不是 http: to access your application, and your ASP.NET application should have the ability to automatically switch to the secure mode (https) if user comes to the application from a non-secure mode (http). http来访问您的应用程序,并且如果用户从非安全模式(http)进入该应用程序,则ASP.NET应用程序应具有自动切换到安全模式(https)的能力。

The easiest way to implement this feature is to use Global.asax's Application_BeginRequest function, where it checks if the request comes from a "HTTPS" protocol, if not, then changes "http" to "https" and then redirecst the request to the secure location.

实现此功能的最简单方法是使用Global.asax的Application_BeginRequest函数,该函数在其中检查请求是否来自“ HTTPS”协议(如果不是),然后将“ http”更改为“ https”,然后将请求重新发送到安全的位置。

The code snippets for VB.NET and C# are attached.

随附了VB.NET和C#的代码段。

Note:

注意:

If the application is running on a local machine during the development phase, we should not try to redirect the request to a secure link, that is why there are some checks in the first couple of lines of code.

如果应用程序在开发阶段在本地计算机上运行,​​则我们不应尝试将请求重定向到安全链接,这就是为什么在前几行代码中进行一些检查的原因。

'VB.NET
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
  ' Fires at the beginning of each request
  'Require SSL
  If (Request.UserHostName <> "127.0.0.1" _
	AndAlso Request.UserHostName <> "localhost") Then
      If Request.ServerVariables("HTTPS") = "off" Then
        Dim redir As String = "https://"   Request.ServerVariables("SERVER_NAME")   Request.ServerVariables("SCRIPT_NAME")
        If Request.ServerVariables("QUERY_STRING") <> "" Then
          redir  = "?"   Request.ServerVariables("QUERY_STRING")
        End If
        Response.Redirect(redir)
      End If
  End If
End Sub 
//C#
public void Application_BeginRequest(object sender, EventArgs e)
{
  if (Request.UserHostName != "127.0.0.1" && Request.UserHostName != "localhost")
  {
    if (Request.ServerVariables["HTTPS"] == "off")
	{
	  string redir = "https://"   Request.ServerVariables["SERVER_NAME"]   Request.ServerVariables["SCRIPT_NAME"];
	  if (Request.ServerVariables["QUERY_STRING"] != "")
	  {
	    redir  = "?"   Request.ServerVariables["QUERY_STRING"];
	  }
	  Response.Redirect(redir);
	}
  }
}

翻译自: https://www.experts-exchange.com/articles/1157/Force-ASP-NET-web-application-to-use-SSL.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值