我的网页中有以下步骤
1)用户登录并设置以下会话变量
Session("userName") = reader_login("useremail").ToString()
Session("userId") = reader_login("user_ID").ToString()
Session("firstName") = reader_login("firstName").ToString()
2)现在,在我登录的VB.NET模板中,我引用了一个名为LoggedIn.Master的MasterPage。其中我添加了以下方法来检查上述空会话变量。如果它们为null,则重定向回登录页面。
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
'#Check that User is Logged in, if not redirect to login page
If (Session("userId") Is Nothing) Or (Session("userName") Is Nothing) Or (Session("firstName") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
3)现在我的问题是,如果我想在不同的.net模板中使用任何上述3个Session变量,或者引用上述母版页的usercontrols我需要AGAIN添加支票
If (Session("userId") Is Nothing) Or (Session("userName") Is Nothing) Or (Session("firstName") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
在相应的页面中或将在检入母版页中执行。因为此刻,即在用户控制中,我试图做,即
customerName.Text = Session("userName").ToString()
或
Response.Write(Session("userName").ToString())
我收到错误 对象引用未设置为对象的实例。
customerName.Text = Session(“userName”)。ToString()
答案 0 :(得分:2)
您可以在Session周围编写一个包装器来处理空值,并在访问项目时调用包装器:
Public Class SessionWrapper
Public Shared ReadOnly Property Item()
'Access session here and check for nothing
End Property
End Class
并像这样使用
SessionWrapper.Item("itemName")
答案 1 :(得分:1)
您可以创建一个询问会话对象的http模块,如果它们为null,它将重定向到登录页面并通过开发此http模块,在每个页面请求中模块将进行检查然后您可以使用通常没有检查。
答案 2 :(得分:1)
在回答您的问题时 - 只要母版页检查会话并在所有控件和页面代码引用Session之前重定向,您应该没问题。
您使用OnInit()
似乎是合理的,但请参阅this article以便更好地了解事件的发生时间。
顺便说一句,我强烈反对在您的页面和控制代码中使用Session
的临时调用。相反,我建议您创建一个静态SessionManager类,为您执行Session引用。这样,您就可以从强类型中受益,并且无法在代码中意外地进行难以调试的“会话密钥”拼写错误,例如Session["FiirstName"]
。此外,您可以将空会话检查权限合并到会话值的调用中:
示例(在C#中,抱歉!)
public static class SessionManager
{
private static void EnsureUserId()
{
if (Session["userId"] == null)
{
Response.Redirect("YourLogin.aspx", false);
}
}
public static string FirstName
{
get
{
EnsureUserId();
if (Session["firstName"] == null)
Session["firstName"] = "";
return (string)Session["firstName"];
}
set
{
Session["firstName"] = value;
}
}
}
答案 3 :(得分:0)
处理此问题的更好方法是为需要存在此会话变量的所有控件添加基类。然后,您可以添加属性以包装对会话和其他很酷的东西的访问,即使控件与不同的母版页一起使用,检查也会起作用。