Reputation: 3103
I have a lot of pages in my project. In all pages I write:
if (!IsPostBack)
{
if (HttpContext.Current.Session["curUserRole"] == null)
{
DBUsers.SetUserStatusOnline("0", ViewState["curUserLogin"].ToString());
ViewState["curUserLogin"] = "";
Response.Redirect("~/Login.aspx");
}
else
{
ViewState["curUserLogin"] = HttpContext.Current.Session["curUserLogin"].ToString();
DBUsers.SetUserStatusOnline("1", ViewState["curUserLogin"].ToString());
}
}
When a user logs in on the site, the current user role is written into the session and the current user login is written in the viewstate. When the session finishes, I thought that I could view the current user login in the viewstate and set the offline status in the database. But when session
is null, the viewstate also null. What can I do?
Upvotes: 0
Views: 749
Reputation: 11396
Wouldn't using Forms Authentication be a better approach rather than manually handling roles, viewstate and session?
That way you'd interact with the current Identity to get user information, rather custom storage of information.
And I think you probably shouldn't depend on a postback by the user to determine if the session has expired. What if the user simply closes the browser? He/she would remain "Online" indefinitely.
You should provide a mechanism for the user to manually log out.
Now, if you are using InProc for your session state you can handle Session_End in global.asax to set that user to "Offline" in your database. If you are using StateServer or SQLServer then Session_End is not called on timeout, and you have to handle it in a custom way, such as through a scheduled task on the DB Server to mark users as Offline.
Now, if you really need a very precise control of the Online/Offline status, you might need to go for a more complex approach. One option would be, that whenever a user executes any action, to store a datetime on that last activity on the User table. And consider any user that hasn't done any activity in a specific time to be offline. Another option would be ajax calls used as a keep-alive call to update that datetime mentioned above.
Upvotes: 1
Reputation: 8098
In addition to UnhandledException
's answer, I would also add that it might be better to centralize your logic in a class and then derive your pages from that new class rather than cut-and-pasting it to every page:
public class MyPageClass : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
// Add your logic here.
base.OnLoad(e);
}
}
public class WebPage1 : MyPageClass
{
private void Page_Load(object sender, System.EventArgs e)
{
}
}
Upvotes: 0
Reputation: 63065
If Response.redirect
is used, then ViewState cannot be accessed across pages. try using Server.transfer
check Access ViewState Across Pages for more information.
Upvotes: 2