[英]Active Directory UserPrincipal issue
我有一些基于当前上下文获取用户的代码,这种情况发生在我的应用程序的Page_Load()
方法中。
var context = new PrincipalContext(ContextType.Domain, "dc", "DC=domain,DC=com", "user", "password");
UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name);
string Name = user.Name.Trim();
lblName.Text = Name;
此方法有效,并且标签正确显示了已登录的用户(Windows身份验证)。
但是,我代码的另一部分,在按下按钮时,会在包含其他用户名的数据网格中进行一些循环,并使用类似的方法来获取有关这些用户的信息。
我已经利用页面上的标签来显示相关的用户信息,但是这些标签之一似乎根据循环中要处理的用户而改变,而实际上它只需要引用当前登录的用户。
有没有解决的办法? 我认为通过使用本质上可以完成相同操作的单独方法,我将获得不同的对象。 返回值不同,所以我不确定这是怎么回事。
下面的相关代码,带有一些注释,以解释或指出不相关的代码(发送电子邮件和处理异常-已全部删除)。
public string getUserEmail()
{
var context = new PrincipalContext(ContextType.Domain, "dc", "DC=domain,DC=com", "user", "password"); ;
UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name);
string email = user.EmailAddress;
return email;
}
public string getOtherUserEmail(string user)
{
user = user.Trim();
var context = new PrincipalContext(ContextType.Domain, "dc", "DC=domain,DC=com", "user", "password");
UserPrincipal u = UserPrincipal.FindByIdentity(context, user);
string email2= u.EmailAddress;
return email2;
}
protected void btnEmail_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gdView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label FullName = gdView1.Rows[index].FindControl("lblFullName") as Label; // other username from gridview
string FromAddress = getUserEmail(); //logged in user
try
{
string otherName = FullName.Text.ToString();
string ToAddress1 = getOtherUserEmail(FullName); //Other user
//Generate an email message....
smtpClient.Send(mail);
lblMessage.Text = "Email sent!";
}
catch
{ // exception handling
}
}
}
protected void gdView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = gdView1.Rows[e.RowIndex].Cells[2]; //Cell containing "other" user name
Message.Text = cell.Text;
string otherName = cell.Text.ToString();
string ToAddress = getOtherUserEmail(otherName); //Other user
string FromAddress = getUserEmail(); //logged in user
try
{ //email as above
}
catch
{ // exception handling
}
}
根据您发布的内容,我希望您也能获得不同的对象。 也许您未包含的代码中发生了什么?
另外,对于当前登录的用户,您应该在Page_Load()
之外定义一个字段(称为_loggedOnUser
Page_Load()
。 这样,所有方法都可以访问它。 这也将使您的代码更易于遵循,甚至可以解决您的引用问题。
public partial class Page1 {
UserPrincipal _loggedOnUser;
public void Page_Load() {
var context = new PrincipalContext(ContextType.Domain, "dc", "DC=domain,DC=com", "user", "password");
_loggedOnUser= UserPrincipal.FindByIdentity(context, User.Identity.Name);
string Name = _loggedOnUser.Name.Trim();
lblName.Text = Name;
}
}
然后,您可以在课程的其余部分中引用它,而不必在循环中浪费时间返回Active Directory。
因此,此行: string FromAddress = getUserEmail();
可以更改为string FromAddress = _loggedOnUser.EmailAddress;
这样就避免了再次致电AD来获取已有信息的昂贵费用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.