修改密碼頁面點擊按鈕拋出 `NullReferenceException`,堆疊指向 `Session["PWD"].ToString()`。
`Session["PWD"]` 為 `null`(Session 過期、用戶未登入、應用程式池回收),直接呼叫 `.ToString()` 拋出例外。
protected void Button1_Click(object sender, EventArgs e)
{
// 1. 先檢查 Session 是否存在
if (Session["username"] == null || Session["PWD"] == null)
{
Response.Write("");
Response.Redirect("Login.aspx");
return;
}
// 2. 取值
string oldPwd = Session["PWD"].ToString();
string userId = Session["username"].ToString();
// 3. 輸入驗證
if (string.IsNullOrEmpty(TextBox2.Text) || string.IsNullOrEmpty(TextBox3.Text))
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('密碼不能為空!');", true);
return;
}
if (TextBox1.Text != oldPwd)
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('舊密碼不正確!');", true);
return;
}
if (TextBox2.Text != TextBox3.Text)
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('兩次新密碼不一致!');", true);
return;
}
// 4. 參數化查詢防 SQL 注入
string sql = "UPDATE TB_XueSheng SET PassWord=@pwd WHERE XueHao=@id";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@pwd", TextBox2.Text);
cmd.Parameters.AddWithValue("@id", userId);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('修改成功!');", true);
else
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('修改失敗,用戶不存在');", true);
}
}