我的项目中有一个带有代码的 Global.asax 文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Data.SqlClient;
using WrapperObjects;
using System.Security.Principal;
namespace Application
{
public class Global : System.Web.HttpApplication
{
private string userLogin = string.Empty;
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
}
void Application_Error(object sender, EventArgs e)
{
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
DBUsers.SetUserStatusOnline("0", userLogin);
Session["curUserRole"] = string.Empty;
Session["curUserLogin"] = string.Empty;
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Request.IsAuthenticated && User.Identity is FormsIdentity)
{
SqlConnection myConnection = new SqlConnection(DBConnection.GetConnectionString());
SqlCommand myCommand = new SqlCommand("SELECT * FROM Users WHERE login=@login", myConnection);
myCommand.Parameters.AddWithValue("login", app.Context.User.Identity.Name);
myCommand.Connection.Open();
SqlDataReader Reader = myCommand.ExecuteReader();
string role = string.Empty;
while (Reader.Read())
{
userLogin = Reader["login"].ToString();
role = Reader["role"].ToString();
}
if (role != string.Empty)
{
FormsIdentity fi = (FormsIdentity)app.User.Identity;
app.Context.User = new GenericPrincipal(fi, new string[] { role });
}
}
}
}
}
当用户登录到项目运行功能时protected void Application_AuthenticateRequest(object sender, EventArgs e)
,我尝试将用户登录名存储在私有字符串类型userLogin
变量中。但是当此函数中的会话结束运行函数void Session_End(object sender, EventArgs e)
时,我尝试通过用户登录状态“离线”将其保存在数据库中,但变量userLogin
为空。我在哪里可以快速保存用户登录并在功能中使用它void Session_End(object sender, EventArgs e)
?