asp.net中的身份验证(代码)

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");
}

转载于:https://www.cnblogs.com/lovenets/articles/424254.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值