NullReference when user is not logged in

39 views Asked by At

I can't access a page when is no one logged in. I want to show some buttons when userID match and just show the page with FillPage() if no one is logged.

protected void Page_Load(object sender, EventArgs e)
    {
        FillPage();

        if (!String.IsNullOrWhiteSpace(Request.QueryString["id"]))
        {
            int id = Convert.ToInt32(Request.QueryString["id"]);
            JobReqModel model = new JobReqModel();
            JobDescriptions job = model.GetJob(id);

            if (job.PostedBy == Membership.GetUser().ProviderUserKey.ToString())
            {
                Button2.Visible = true;
                Button3.Visible = true;
                Button4.Visible = true;
                Lineseparator.Visible = true;
            }

            else
            {
                Button2.Visible = false;
                Button3.Visible = false;
                Button4.Visible = false;
                Lineseparator.Visible = false;
            }
        }

I get NullReference on this line

if (job.PostedBy == Membership.GetUser().ProviderUserKey.ToString())

I understand why is NULL but how I avoid this expcetion? I tried to test if ProviderUserKey is null and just use Fillpage after that.

1

There are 1 answers

1
Raphaël Althaus On BEST ANSWER

Just add a null check.

Caus if GetUser() returns null, you have an NRE when trying to access its ProviderUserKey property.

if (MemberShip.GetUser() != null && Membership.GetUser().ProviderUSerKey.ToString() == josb.PostedBy)