【发布时间】:2011-07-17 20:09:03
【问题描述】:
我有一个母版页,其中设置了一些我想在整个站点中使用的变量..
protected void Page_Load(object sender, EventArgs e)
{
//Get users name from AD
str_DomainName = HttpContext.Current.User.Identity.Name;
str_CurrentLogin = str_DomainName.Substring(5);
//Display current user information
DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", str_CurrentLogin);
SearchResult result = search.FindOne();
DirectoryEntry entry = result.GetDirectoryEntry();
lbl_CurrentUser.Text = result.Properties["givenName"][0].ToString() + ' ' + result.Properties["sn"][0].ToString();
// Get SID
IntPtr logonToken = WindowsIdentity.GetCurrent().Token;
WindowsIdentity windowsId = new WindowsIdentity(logonToken);
//Set session variabls
this.CurrentFirstName = result.Properties["givenName"][0].ToString();
//this.CurrentEmail = result.Properties["mail"][0].ToString();
//this.CurrentSID = windowsId.User.ToString();
//this.CurrentUserName = str_CurrentLogin;
//this.CurrentFullName = lbl_CurrentUser.Text;
//this.CurrentDomain = str_DomainName;
this.Session.Add("currentEmail", result.Properties["mail"][0].ToString());
}
public String CurrentFirstName
{
get { return (String)ViewState["currentFirstName"]; }
set { ViewState["currentFirstName"] = value; }
}
然后我在我的 defalut.aspx 页面中调用它们如下:
protected void Page_PreRender(object sender, EventArgs e)
{
//try
//{
lbl_FullName.Text = Master.CurrentFullName;
lbl_SID.Text = Master.CurrentSID;
testLabel.Text = Master.CurrentEmail;
//}
//catch (Exception ex)
//{ }
}
这很好用。但是如果我离开默认页面,则会收到以下错误。
对象引用未设置为对象的实例。
lbl_FullName.Text = Master.CurrentFullName; 一行
如果我取消注释 try catch 那么它工作正常,但我不认为这是避免错误的正确方法..
我只是 ASP 的新手,所以请善待..
编辑:
Master.cs 中的变量设置如下。
public String CurrentUserName
{
get { return (String)ViewState["currentUserName"]; }
set { ViewState["currentUserName"] = value; }
}
【问题讨论】:
-
这可能取决于处理各种事件的顺序(即,您可能正在尝试在主页中设置值之前从页面读取值)。查看this 并尝试检查事件顺序
-
什么是主变量?它是在其他页面上设置还是默认设置?
-
查看我的编辑以了解我如何生成变量
-
见stackoverflow.com/questions/4660142/… 的根本原因:“因为你没有初始化变量”。