ASP.Net登录窗体与Session操作

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




实现效果:(一分钟后无任何操作后Success.aspx页面将过期,返回Login.aspx页面)

实现效果

数据库表结构:

数据库表

注意:新建Login.aspx和Success.aspx,Login.aspx页面拖拽两个TextBox控件和一个Button控件

Login.aspx.cs代码:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string username = this.TextBox1.Text.Trim();
        string password = this.TextBox2.Text.Trim();
        string testDB = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString;
        SqlConnection conn = new SqlConnection(testDB);
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from T_login where username=@username and password=@password";
            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@password", password);
            SqlDataReader dr = cmd.ExecuteReader();
            if (username.Equals("") || password.Equals(""))//用户名或密码为空
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('不能为空');", true);
            }
            else
            {
                if (dr.Read())
                {
                Session["name"] = TextBox1.Text.Trim();
                Session.Timeout = 1; //一分钟过期
                Response.Redirect("Success.aspx");
                //Session.Abandon();//清除全部Session
                //清除某个Session
                //Session["name"] = null;
                //Session.Remove("name");
                //ClientScript.RegisterStartupScript(this.GetType(), "", "alert('登录成功');", true);
            }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "alert('登录失败');", true);
                }
            }
            dr.Close();
            conn.Close();
    }
}

Success.aspx.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Success : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["name"] == null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {
            Response.Write("管理员" + Session["name"] + "成功登录!");
        }
    }
}

原文链接:https://www.idaobin.com/archives/1139.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

电子邮件地址不会被公开。 必填项已用*标注

74 + = 75