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