我有兩頁稱爲Login.aspx
和Home.aspx
登錄錯誤消息,對象引用
更新的代碼:
protected void Button1_Click(object sender, EventArgs e)
{
if (loginmethod(txt_us.Text, txt_pwd.Text) != "NA")
{
FormsAuthentication.Initialize();
String strRole = Assignroles(txt_us.Text);
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, txt_us.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, strRole, FormsAuthentication.FormsCookiePath);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(fat)));
loginmethod(txt_us.Text, txt_pwd.Text);
Response.Redirect("home.aspx");
}
else if (Session["ID"] != null)
{
u = Session["ID"].ToString();
}
else
{
Label1.Text = ("Incorrect UserName/Password");
Label1.Visible = true;
Response.Redirect("home.aspx");
}
txt_us.Text = "";
txt_pwd.Text = "";
}
private string loginmethod(string UserName, string Password)
{
try
{
login_class lg_class = new login_class();
Entities login = new Entities();
string logn = Convert.ToString(lg_class.loginfunction(UserName, Password).Rows[0]["id"]);
Session["ID"] = logn.ToString();
return (logn);
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
}
private string Assignroles(string username)
{
if ((txt_us.Text != string.Empty) && (txt_pwd.Text != string.Empty))
return "";
else
return string.Empty;
}
public DataTable loginfunction(string username, string password)
{
try
{
Entities lg = new Entities();
List<SP_GetLogin_Result> gr = lg.SP_GetLogin(username, password).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
foreach (var l in gr)
{
dt.Rows.Add(l.id);
}
return dt;
}
catch (Exception)
{
throw new Exception();
}
}
而且在home.aspx
頁面加載:
string id;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
id = Session["ID"].ToString();
this.FFID = "All";
vehcileinfo(id);
}
}
SP_GetLogin
回ID即用戶名abc
和密碼1224
然後返回ID CU-2343
當我用正確的用戶名和密碼,然後輸入這個重定向到home.aspx
但是,當我輸入錯誤的用戶名或密碼,那麼這表明在這一行
u = Session["ID"].ToString();
System.NullReferenceException錯誤:對象引用未設置爲對象的 實例。
,我想顯示在login.aspx
「不正確的用戶名和密碼」
我該怎麼辦這個問題?
*對象引用不設置到對象的實例。*它的顯示,你的'會議[ 「ID」]''是NULL' –
處理它:'if(Session [「ID」]!= null){u = Session [「ID」]。ToString(); }' –
ON home.aspx頁面?? @Div和是的,我輸入錯誤的用戶名和密碼,這就是爲什麼這個錯誤顯示,因爲我想顯示消息登錄.aspx,不正確的用戶名/密碼.. –