asp.net 实现登陆实例
时间: 2024-05-06 18:17:55 浏览: 7
以下是一个简单的 ASP.NET 登录示例:
1. 创建一个 ASP.NET 网站项目,并在 Default.aspx 页面上添加以下 HTML 控件:
```html
<div>
<h2>登录</h2>
<hr />
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="txtUserName" /></td>
</tr>
<tr>
<td>密 码:</td>
<td><input type="password" id="txtPassword" /></td>
</tr>
<tr>
<td> </td>
<td><input type="button" value="登录" onclick="login();" /></td>
</tr>
</table>
</div>
```
2. 添加一个名为 Login.aspx 的新页面,用于验证用户名和密码,并将用户重定向到 Default.aspx 页面。
```csharp
using System;
using System.Data.SqlClient;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
{
txtUserName.Text = Request.Cookies["UserName"].Value;
txtPassword.Attributes["value"] = Request.Cookies["Password"].Value;
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string userName = txtUserName.Text.Trim();
string password = txtPassword.Text.Trim();
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
{
Response.Write("<script>alert('用户名和密码不能为空!');</script>");
return;
}
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select * from UserInfo where UserName=@UserName and Password=@Password", conn);
cmd.Parameters.AddWithValue("@UserName", userName);
cmd.Parameters.AddWithValue("@Password", password);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if (chkRemember.Checked)
{
Response.Cookies["UserName"].Value = userName;
Response.Cookies["Password"].Value = password;
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(7);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(7);
}
else
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
}
Session["UserName"] = userName;
Response.Redirect("Default.aspx");
}
else
{
Response.Write("<script>alert('用户名或密码错误!');</script>");
}
dr.Close();
conn.Close();
}
}
```
3. 在 Default.aspx.cs 页面中添加以下代码,以检查用户是否已登录并显示其用户名:
```csharp
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["UserName"] != null)
{
lblUserName.Text = "欢迎您," + Session["UserName"].ToString() + "!";
}
else
{
Response.Redirect("Login.aspx");
}
}
}
```
这样,当用户访问 Default.aspx 页面时,如果他们没有登录,则会被重定向到 Login.aspx 页面进行身份验证。如果验证通过,则将用户重定向回 Default.aspx 页面,并在页面上显示其用户名。