如果存在userName和密码,我在数据库中有简单的身份验证类型 我创建FormsAuthenticationTicket并添加它HttpContext.Current.Response.Cookies.Add(cookie);当我在请求之前检查HttpContext.Current.User.Identity.IsAuthenticated时返回false 但是,如果我检查global.asax Application_AuthenticateRequest(对象发送者,EventArgs e)以获取以下请求HttpContext.Current.User.Identity.IsAuthenticated返回true
public static bool Login(string userName, string pass)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
string comand = string.Format("Select * From ChatUser Where " +
"userName = '{0}' and pass ='{1}'", userName, pass);
SqlCommand cmd = new SqlCommand(comand, conn);
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
conn.Close();
return false;
}
while (reader.Read())
{
string id = reader["id"].ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, id, DateTime.Now, DateTime.Now.AddMinutes(30),
false, null, FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
HttpContext.Current.Response.Cookies.Add(cookie);
}
conn.Close();
JoinMesage();
return true;
}
catch (Exception ex)
{
//write in log file
return false;
}
}
}
public static void JoinMesage()
{
string userId;
if (HttpContext.Current.User != null)
{
userId = HttpContext.Current.User.Identity.Name;
using (SqlConnection conn = new SqlConnection(connectionString))
{
string comand = string.Format("Insert into Messages (userID,mesageDate,userStatus)"
+ " Value('{0}','{1}','{2}')", userId, DateTime.Now, true);
}
}
}
答案 0 :(得分:2)
请修改您的机票。它应该是
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
id,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
null,
FormsAuthentication.FormsCookiePath);
并在自定义标识类中设置身份验证类型 请点击链接:
它会解决它。