ASP.NET 登录源代码


今天上ASP.NET课的任务是完成一个登录界面。 下面我把源代码分享给大家。

[code lang="java"] using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Collections; public partial class _UserLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.Image1.ImageUrl = "ValidateCode.aspx"; //验证码网页 } } //单击登陆先判断验证码正确后判断用户名和密码; protected void Button1_Click(object sender, EventArgs e) //点击 登录按钮 { //创建连接 SqlConnection con = new SqlConnection("server=.;database=login;uid=sa;pwd=sa;"); //SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["connString"]); if (Session["CheckCode"].ToString().Equals(TextBoxYzm.Text.ToString().ToUpper())) { try { con.Open(); SqlCommand com = new SqlCommand("select @count=count(*) from loginInfo where name=@name and pwd=@ps", con);//在数据表loginInfo中查找用户名和密码 用参数的方式更具有安全性 com.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar, 50)); com.Parameters["@name"].Value = TextName.Text; com.Parameters.Add(new SqlParameter("@count", SqlDbType.Int, 4)); com.Parameters["@count"].Direction = ParameterDirection.Output; com.Parameters.Add(new SqlParameter("@ps",SqlDbType.VarChar, 50)); com.Parameters["@ps"].Value = FormsAuthentication.HashPasswordForStoringInConfigFile(TextPass.Text, "MD5");//给密码字段加密 com.ExecuteNonQuery(); int i = int.Parse( com.Parameters["@count"].Value.ToString()); if (i > 0) { //添加登陆日志 com = new SqlCommand("insert LoginLog values('" + TextName.Text + "','" + DateTime.Now.ToString() + "')", con); com.ExecuteNonQuery(); con.Close(); FormsAuthentication.RedirectFromLoginPage(TextName.Text, true);//写入身份认证cookie } else { Response.Write("<script>alert('密码或用户名错误!')</script>"); } } catch (Exception error) { Response.Write(error.ToString()); } } else Response.Write("<script>alert('验证码错误!')</script>"); } protected void LinkButton2_Click(object sender, EventArgs e) //点击 看不清 按钮 { this.Image1.ImageUrl = "ValidateCode.aspx"; //刷新验证码 } } [/code]

要运行以上代码需要数据库的