简体   繁体   English

检查用户是否使用会话登录

[英]Check if user is logged in using sessions

I want to check if a user is logged in and if they are, deny them access to the registration and login pages. 我想检查用户是否登录以及是否登录,请拒绝他们访问注册和登录页面。 When a user logs in I'm setting these session variables: 当用户登录时,我正在设置以下会话变量:

HttpContext.Current.Session["LoggedIn"] = true;
HttpContext.Current.Session["FullName"] = (string)Reader["FirstName"] + " " + (string)Reader["LastName"];
Response.Redirect("Default.aspx");

And I'm checking them at the top of the register and login pages like so: 我在注册和登录页面的顶部检查它们,如下所示:

if ((bool)HttpContext.Current.Session["LoggedIn"])
{
    Response.Redirect("Default.aspx");
}

However, when I try to go to the page while not logged in this exception gets thrown: 但是,当我尝试不登录而转到该页面时,会抛出此异常:

Object reference not set to an instance of an object. 你调用的对象是空的。

I'm assuming it's ebcause the LoggedIn key doesn't exist because I only create it after a successful login. 我认为这是因为LoggedIn键不存在,因为我仅在成功登录后才创建它。

So, how can I check if the LoggedIn key exists and if it doesn't, redirect the user to Default.aspx ? 因此,如何检查LoggedIn键是否存在,如果不存在,则将用户重定向到Default.aspx

Thanks! 谢谢!

I think you can do a simple null check on this like.... 我认为您可以对此进行简单的null检查。

if (HttpContext.Current.Session["LoggedIn"] != null)
{
   // once inside this loop
   // you can now read the value from Session["LoggedIn"]
   Response.Redirect("Default.aspx");
}

you need to make shure that the object is not null before unboxing it 您需要先确定该对象不为空,然后再将其拆箱

if(HttpContext.Current.Session["LoggedIn"]!=null)
{

  if ((bool)HttpContext.Current.Session["LoggedIn"])
   {
    Response.Redirect("Default.aspx");
    }
}

Why to avoid the default webforms authentication model altogether? 为什么要完全避免使用默认的Webforms身份验证模型? Simply use web.config to define a restricted area, set all the settings correctly and you won't have to perform checks like this for every page. 只需使用web.config定义一个限制区域,正确设置所有设置,您就不必对每个页面执行类似的检查。

But, if you want to reinvent the wheel.... 但是,如果您想重新发明轮子……
You check for something that probably doesn't exist yet. 您检查是否可能还不存在。 You must modify your if-statement like this: 您必须像这样修改if语句:

bool isLoggedIn = (HttpContext.Current.Session["LoggedIn"] == null ? false : (bool)HttpContenxt.Current.Session["LoggedIn"];

if (isLoggedIn)
{
    Response.Redirect("Default.aspx");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM