Object reference not set to an instance of an object.how to redirect to login page if session is null
当我在浏览器上打开 Web 表单页面但我收到此错误
1 | Object reference not set to an instance of an object |
请检查代码片段,我做错了什么
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | if (!IsPostBack) { if (string.IsNullOrEmpty(Session["LoginUser"].ToString()) == false && string.IsNullOrEmpty(Session["CustomerId"].ToString()) == false)//error { if (Session["LoginUser"].ToString() =="admin") { DDlUsers.Visible = true; fillusers(); } else if (Session["LoginUser"].ToString() !="admin" && Session["CustomerId"].ToString() =="True") { DDlUsers.Visible = false; //fillusers(); } else { DDlUsers.Visible = false; } FillProjectList(); Pnl_Link.Visible = false; Pnl_Status.Visible = false; } else { Response.Redirect("~/login.aspx"); } } |
如果会话为空,如何使其重定向到 login.aspx。不抛出运行时异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | if (!IsPostBack) { if (Session["LoginUser"]!=null && Session["CustomerId"]!=null && !string.IsNullOrEmpty(Session["LoginUser"].ToString()) && !string.IsNullOrEmpty(Session["CustomerId"].ToString()))//error { if (Session["LoginUser"].ToString() =="admin") { DDlUsers.Visible = true; fillusers(); } else if (Session["LoginUser"].ToString() !="admin" && Session["CustomerId"].ToString() =="True") { DDlUsers.Visible = false; //fillusers(); } else { DDlUsers.Visible = false; } FillProjectList(); Pnl_Link.Visible = false; Pnl_Status.Visible = false; } else { Response.Redirect("~/login.aspx"); } } |
只需在
之后的第一个 if 条件中添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | if (!IsPostBack) { if (Session["LoginUser"]!=null && string.IsNullOrEmpty(Session["LoginUser"].ToString()) == false && string.IsNullOrEmpty(Session["CustomerId"].ToString()) == false)//error { if (Session["LoginUser"].ToString() =="admin") { DDlUsers.Visible = true; fillusers(); } else if (Session["LoginUser"].ToString() !="admin" && Session["CustomerId"].ToString() =="True") { DDlUsers.Visible = false; //fillusers(); } else { DDlUsers.Visible = false; } FillProjectList(); Pnl_Link.Visible = false; Pnl_Status.Visible = false; } else { Response.Redirect("~/login.aspx"); } } |