蛙蛙推荐:asp.net中的身份验证
我用的是基于窗体的验证,这也是最常用的,我只写一下摘要,源代码太长,但应该不影响理解代码.
web.config的修改:
<authentication mode="Forms" />
用户的登陆验证方法,:
这里有两个输入控件的,一个是user_tb,用来输入用户,一个是psw_tb,用来输入密码
private void Button1_Click(object sender, System.EventArgs e)
{
//用户登陆验证
string ip= System.Web.HttpContext.Current.Request.UserHostAddress ;
string user_name=user_tb.Text;
string user_psw=psw_tb.Text;
user_name=user_name.Replace("<","<").Replace(">",">").Replace(" "," ").Replace("'","‘");
user_psw=user_psw.Replace("<","<").Replace(">",">").Replace(" "," ").Replace("'","‘");
if(user_name!=""||user_psw!="")
{
SqlConnection myconn=new SqlConnection((string)ConfigurationSettings.AppSettings["connstring"]);//连接数据库
myconn.Open();//打开
string validate_Sql="select * from Web_User where User_Name='"+user_name+"'and User_Psw='"+user_psw+"'";
SqlCommand validate_com=new SqlCommand(validate_Sql,myconn);
SqlDataReader validate=validate_com.ExecuteReader();
string temp="";
while(validate.Read())
{
Session["user_name"]=user_name;
Session["user_flag"]=validate["User_Flag"].ToString();
temp="yes";
}
validate.Close();
if(temp=="yes")
{
user_tb.Text="";
psw_tb.Text="";
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(user_name,false);
Response.Redirect("manage_index.aspx");
}
else
{
Response.Write("<script>alert('您的用户名或密码错误!');</script>");
return ;
}
user_tb.Text="";
psw_tb.Text="";
myconn.Close();
}
}
判断用户是否已经登陆:
private void Page_Load(object sender, System.EventArgs e)
{
//在这里判断用户是否已经登陆
if(!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Write("<script>alert('您没有登陆!');history.back()</script>");
}
string strUsername;
strUsername=System.Web.HttpContext.Current.User.Identity.Name+"<br>+System.Web.HttpContext.Current.User.Identity.IsAuthenticated";
lbIUsername.Text=strUsername;
// 在此处放置用户代码以初始化页面
}
用户的退出:
private void LinkButton1_Click(object sender, System.EventArgs e)
{ //退出
Session["user_name"]=null;
Session["user_flag"]=null;
Session.Clear();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("default.aspx");
}