Comparing the value of a session variable with a string

I am comparing a session variable with a string to check if the login type is administrator or not.

The code I'm using is:

if (Session["loggedInUsername"] == null)
        {
            btnLogin.Text = "Sign In";
            lblWelcome.Text = "Welcome!";
            hypManageRestaurants.Enabled = false;
            hypManageReviews.Enabled = false;
            hypPostReviews.Enabled = false;

        }
        else
        {
            if (Session["loggedInUserType"] == "Administrator")
            {
                hypManageRestaurants.Enabled = true;
                hypManageReviews.Enabled = true;
                hypPostReviews.Enabled = true;
            }
            else
            {
                hypManageRestaurants.Enabled = false;
                hypManageReviews.Enabled = false;
                hypPostReviews.Enabled = true;
            }
            lblWelcome.Text = "Welcome " + Session["loggedInUsername"];

            btnLogin.Text = "Sign Out";
        }

So first, I check if any user is registered or not. If the user logs in successfully, the session variable "loggedInUsername" will have the username value. If the session variable "loggedInUsername" is not empty, it will check the session variable "loggedInUserType" for the type of registered user.

Here's the strange thing, the value of "loggedInUserType" is exactly "Administrator" without "", in the if function, where I compare the session variable with the string "Administrator", it is skipped and proceeds differently.

, .

, , , "".

+5
8

((string)Session["loggedInUserType"]) == "Administrator"
+3

if(Convert.ToString(Session["loggedInUserType"]) == "Administrator) ...

+4

:

if (Session["loggedInUserType"].ToString().Trim()
        .Equals("Administrator", StringComparison.InvariantCultureIgnoreCase))
+1

, [ "loggedInUserType" ]?

0
if (Session["loggedInUserType"].ToString() == "Administrator")
0

Session Object, , , , .

string:

if (((string)Session["loggedInUserType"]) == "Administrator")
0

You can do it:

string session = (string)Session["loggedInUserType"]

if (session == "Administrator")

or yours Sessioncan be in a particular class using getters.

0
source
if(Convert.ToString(Session["loggedInUserType"]) == "Administrator)

Thus, there is no need to check the null value becuase Convert.ToString handle Null value return "" empty string

0
source

All Articles