Ответ 1
Это работает для меня.
Вы должны иметь возможность различать разные пользователи на разных контроллерах домена (например, домен/имя пользователя), потому что ldappaths будут разными. И, согласно вам, вам все равно, потому что вы не указали ldappath.
Вы делаете ставку на удаление домена /User.Identity.Name. но я не уверен, о чем вас беспокоит, вам просто нужно нарезать строку на две половины и в первый раз, когда вы столкнетесь с этим "время", чтобы нарезать.
и если вам это не нравится, вы можете использовать "правильный путь": http://msdn.microsoft.com/en-us/library/ms973834.aspx
Это тоже хорошо http://geekswithblogs.net/mhamilton/archive/2005/09/30/55621.aspx
/// This is some imaginary code to show you how to use it
Session["USER"] = User.Identity.Name.ToString();
Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D
string ldappath = "LDAP://your_ldap_path";
// "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn");
Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName");
Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail");
Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName");
Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn");
/// working code
public static string GetAttribute(string ldappath, string sAMAccountName, string attribute)
{
string OUT = string.Empty;
try
{
DirectoryEntry de = new DirectoryEntry(ldappath);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))";
SearchResultCollection results = ds.FindAll();
foreach (SearchResult result in ds.FindAll())
{
OUT = GetProperty(result, attribute);
}
}
catch (Exception t)
{
// System.Diagnostics.Debug.WriteLine(t.Message);
}
return (OUT != null) ? OUT : string.Empty;
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
Для домена/имени пользователя
public static string GetDomain(string s)
{
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop + 1) : null;
}
public static string GetLogin(string s)
{
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
}
Для имени пользователя @domain style
public static string GetDomain(string s) //untested
{
int stop = s.IndexOf("@");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
}
public static string GetLogin(string s) //untested
{
int stop = s.IndexOf("@");
return (stop > -1) ? s.Substring(0, stop) : null;
}