page_load event in Master and Content Pages

淺唱寂寞╮ 提交于 2019-12-06 15:40:16

Presumably, when you say you are using the Session["loggedInUser"] value, you are then calling .ToString() method or similar to display it?

In which case, you will need to check for a null object before using it. It would be best practice to check for the existance of the object before using any methods on it in any case, so:

if (Session["loggedInUser"] != null)
{ ... }

Only if you are certain that the code will never be executed without the Session object being instantiated can you use methods without checking for a null reference.

http://msdn.microsoft.com/en-us/library/03sekbw5.aspx

Finally I've come up with a solution:

I create a class BasePage like this:

public class BasePage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        if (Session["loggedInUser"] == null)
        {
            Response.Redirect("~/Login.aspx");
        }
        base.OnLoad(e);
    }
}

And in the content page, instead of inheriting from Page, I change to BasePage and it works perfectly

Thanks for all of your support

Nice day ;)

You could check for Session["loggedInUser"] in the content Page's Page_PreRender() rather than Page_Load()or alternatively, do the master page check in the Page_Init() rather than Page_Load(). We had the same problem and went with the Master page Page_Init() option, so that we could still use Page_Load() in all the Content pages.

Edit: It's Page_Init() not PreInit().

I have 2 masterpages(1 for prelogin,2nd for afterlogin),home page is independent,logout page inherits postlogin page) in all postloginpage session chck if sessionnull(xyz)else(redirect loginpage) all this in Page_Init event of afterlogin.master................Successfull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!