I have a function that checks for Session and Cookies and redirects user based on those.
private void CheckRecruiterLogin()
{
List<string> list = new List<string>();
if (Session["Candidate"] != null ||
Request.Cookies["Candidate"] != null)
{
list = (List<string>)Session["Candidate"];
string status = list[1].ToString();
if (status.Equals("applicant") ||
Request.Cookies["Candidate"]["Status"].Equals("applicant"))
{
Response.Redirect("ApplicantHome.aspx");
}
if (status.Equals("preboarding") ||
Request.Cookies["Candidate"]["Status"].Equals("preboarding"))
{
Response.Redirect("PreboardingHome.aspx");
}
else if (status.Equals("hiring") ||
Request.Cookies["Candidate"]["Status"].Equals("hiring"))
{
Response.Redirect("HiringHome.aspx");
}
}
else if (Session["HR"] != null || Request.Cookies["HR"] != null)
{
list = (List<string>)Session["HR"];
string type = list[1].ToString();
if (type.Equals("preboarder") ||
Request.Cookies["HR"]["Type"].Equals("preboarder"))
{
Response.Redirect("PreboarderList.aspx");
}
else if (type.Equals("datamanager") ||
Request.Cookies["HR"]["Type"].Equals("datamanager"))
{
Response.Redirect("HiringList.aspx");
}
else if (type.Equals("admin") ||
Request.Cookies["HR"]["Type"].Equals("admin"))
{
Response.Redirect("AdminHome.aspx");
}
}
else if (Session["HR"] == null &&
Request.Cookies["HR"] == null)
{
Response.Redirect("index.aspx");
}
}
But the application throws a runtime exception saying Object reference not set to an instance of an object.
I believe this is because there are no cookies present.
My question is: Should I separate the checking of sessions and cookies, or can I do it in one statement?
Thanks!
Your code requires both the cookie, and the session.
If this is intended, you want to change the condition to use
&&
instead of||
.However, it's more likely you intend the code to use session if available, and cookies if session isn't there. This is quite simply done by storing the value in a variable, and using that later:
That said, using cookies for security checks like this is a bad idea - they are user visible and user editable.
Also, there's no point in using
Equals
- just use==
. This isn't Java, .NET actually compares the value, not the reference. Although it's probably a better idea to actually do the comparison using invariant culture, case insensitive equality. There's also no point in creatingnew List<string>
- the value is never used. Just declare the variable at the point where you already have something to fill it with.