我已经编写了一个代码,我认为该代码最好能够获取当前访问该网站的用户。但是,它将显示托管页面的服务器的控制台ID。下面是代码..需要建议。
代码正在从LDAP获取用户详细信息。
请让我知道是否需要提供更多详细信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Security.Principal;
namespace UserDetail
{
public partial class UserDet : System.Web.UI.Page
{
public DirectorySearcher dirSearch = null;
protected void Page_Load(object sender, EventArgs e)
{
//string username = Environment.UserName; //Or you put your username if you have any one
//string pswd = "test"; //Provide paassword to login to LDAP
//string domain = Environment.UserDomainName; //Provide Domain Name your own
string username = "test"; //Username for Authentication
string pswd = "test"; // password for Authentication
string domain = "abc.com"; // Provide Domain name
// GetUserInformation(username,pswd,domain);
Label1.Text = Environment.UserName.ToString();
}
public void GetUserInformation(string username, string passowrd, string domain)
{
string searchUsername = Environment.UserName; //Provide username to be search
SearchResult rs = null;
rs = SearchUserByUserName(GetDirectorySearcher(username, passowrd, domain), searchUsername);
if (rs != null)
{
if (rs.GetDirectoryEntry().Properties["samaccountname"].Value != null)
Label1.Text = "Username : " + rs.GetDirectoryEntry().Properties["samaccountname"].Value.ToString();
}
}
public SearchResult SearchUserByUserName(DirectorySearcher ds, string username)
{
ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + username + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult userObject = ds.FindOne();
if (userObject != null)
return userObject;
else
return null;
}
public DirectorySearcher GetDirectorySearcher(string username, string passowrd, string domain)
{
try
{
var de = new DirectoryEntry("LDAP://" + domain); // Without authentication
//var de= new new DirectoryEntry("LDAP://" + domain, username, passowrd); // With authentication
dirSearch = new DirectorySearcher(de);
}
catch (DirectoryServicesCOMException e)
{
Label1.Text= e.Message.ToString();
}
return dirSearch;
}
}
}
答案 0 :(得分:0)
使用以下代码获取登录用户的Windows用户名。
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring()