Ido
Ido

Reputation: 420

I can't get a session's value and use it inside an if() statement

I want to check the value of a session in my ASP.NET website (WebForms). So what I have tried to do is:

// This file called 'Encryptor.cs' and is located under the 'App_Code' folder.

using System;
using System.Data;
using System.Data.OleDb;
using System.Security.Cryptography;
using System.Text;

public static class Encryptor
{
    public static bool CheckLoginStatus()
    { 
        bool LoginStatus = false;

        if ((string)Session["username"] == null)
        { 
             LoginStatus = true;
        }

        return LoginStatus;
    }
}

I keep getting this message: "The name 'Session' does not exist in the current context." How do I fix it?

Upvotes: 0

Views: 2520

Answers (1)

schei1
schei1

Reputation: 2487

You should be able to access the Session variable like this:

string username = (string)System.Web.HttpContext.Current.Session["username"]; 

The HttpContext resides in the System.Web namespace. You could either reference the namespace via a using System.Web, or go full namespace when accessing the session.

If you want to expand the usefulness of Session, and have strong typing on the variables, then you could opt in for this solution: How to access session variables from any class in ASP.NET?

Upvotes: 1

Related Questions