我有两个名为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
和pssword 1224
时,此返回ID CU-2343
当我输入正确的用户名和密码时,此重定向到home.aspx
但是当我输入错误的用户名或密码时,这会在此行显示错误
u = Session["ID"].ToString();
System.NullReferenceException:对象引用未设置为 对象的实例。
我想在login.aspx
上显示错误消息
&#34;用户名和密码不正确&#34;
我是怎么做到的?
答案 0 :(得分:1)
根据评论中的讨论,获得NullReferenceException
这意味着,您正在尝试使用null的内容。这意味着您要么将其设置为null,要么根本不将其设置为任何内容。
所以,只需查看Home.aspx的Page_Load
if(Session["ID"] != null)
{
id = Session["ID"].ToString();
}
else
{
// Do logic here
}