ASP.NET 无 Cookie 会话登录






2.65/5 (46投票s)
2003年8月12日

310329
在不使用 Cookie 的情况下,最简单的用户身份验证方法。
引言
以下描述了我在 ASP.NET 网站上强制用户为每个会话登录,但无需他们接受 Cookie 的最简单方法。您需要执行以下操作:
- 创建一个 Web.config 文件,其中包含适当的条目以允许会话状态管理。
- 创建一个格式良好的 Global.asax 文件,其中包含以下代码:
- 创建一个登录页面,以根据您希望的任何方法(例如数据库)对用户进行身份验证。
代码用法
Global.asax 中所需的代码
' Fires when the session is started and sets the default loggedin state to ""
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session("Loggedin") = ""
CheckLoggedIn()
End Sub
' Called when the request has been process by the Request Handler and
' HttpSessionState is available [This is the key piece of code that forces
' the user is login check with each page request]
Sub Application_OnPostRequestHandlerExecute()
CheckLoggedIn()
End Sub
'Check that the user is logged in.
Sub CheckLoggedIn()
'If the user is not logged in and you are not currently on the Login Page.
If Session("LoggedIn") = "" And InStr(Request.RawUrl, "Login.aspx") = 0 Then
Response.Redirect("~/Login/Login.aspx")
End If
End Sub
最后,创建一个 Login.aspx 文件来验证用户。如果允许用户登录,请设置:Session(""Loggedin"") = "Yes"
就这样了。希望这有帮助!祝您使用愉快!