【问题标题】:handling sessions on every page of website处理网站每个页面上的会话
【发布时间】:2016-01-26 12:43:14
【问题描述】:
我有一个数据驱动的网站,当前用户 ID 存储在 Session["UserId"] 中。因此,几乎所有页面中显示的所有数据都是特定于用户的。当用户匿名使用该网站时,这是我展示的一组不同的结果,与 UserId 无关。
我的问题是我必须检查 Session["UserId"] 是否在我使用 Session["UserId"] 的每一行都不为空,我不知何故觉得这不是正确的方法。
有没有一种方法可以检查 page_load 上的 Session 是否不为空?如果我的会话结果为空,我该如何处理?该页面甚至根本无法加载。
希望我能解释一下
【问题讨论】:
标签:
asp.net
session
architecture
webforms
【解决方案1】:
不要在每个页面上检查会话,而是将会话控件放在基类中,并使所有页面都扩展该类。每次您的页面启动时,Page_Init 基本方法都会检查用户是否已通过身份验证。如果未通过身份验证,该方法将抛出一个异常,该异常将被Page_Error 方法捕获。此方法将清除会话资源并重定向到默认页面。
为会话控制创建一个分层类:
public class UserSession { }
public class AnonymousSession : UserSession {}
在您的页面登录上,根据登录类型将UserId 放在会话中:
bool isAnon = GetAnonymous(); // Check form page if login is anonymously
UserSession user;
if(isAnon)
user = new AnonymousSession();
else
user = new UserSession();
Session.Contents.Add("UserId", user);
在PageBase 中设置一个名为Anonymously 的属性,告诉您用户是否匿名输入,并在您的页面中使用它来设置每个页面的设置结果:
public class PageBase: System.Web.Ui.Page
{
// Check here if session type is anonymous
protected bool Anonymously
{
get
{
return (UserSession)Session.Contents["UserId"] is AnonymousSession;
}
}
protected void Page_Init(object Sender,System.EventArgs e)
{
var user = (UserSession)Session.Contents["UserId"];
if (user == null)
{
throw new SessionException();
}
}
protected void Page_Error(object sender, System.EventArgs e)
{
Exception ex = Server.GetLastError();
Server.ClearError();
if(ex is SessionException)
{
Context.Session.Clear();
Context.Session.Abandon();
FormsAuthentication.SignOut();
Server.Transfer("Default.aspx", true);
}
}
}