示例代码为Asp.Net MVC程序,仅供参考!
需要引用命名空间:
using System.DirectoryServices;
Login.cshtml代码:
@{ ViewBag.Title = "模拟域验证"; Layout = "~/Views/Shared/_Layout.cshtml"; } < h2 > 模拟域验证 </ h2 > @using (Html.BeginForm()) { < p > 用户名:@Html.TextBox("UserName") </ p > < p > 旧密码:@Html.Password("OldPassword") </ p > < p > 新密码:@Html.Password("NewPassword") </ p > < p >< input type ="submit" value ="登录" /></ p > } @ViewData["Msg"]
cs代码:
[AcceptVerbs(HttpVerbs.Post)] [ValidateInput( false )] public ActionResult Login( string UserName, string OldPassWord, string NewPassWord) { DirectoryEntry AD = new DirectoryEntry(); AD.Path = string .Format( " LDAP://{0} " , IPAddress); AD.Username = " domain " + @" \ " + UserName; AD.Password = OldPassWord; AD.AuthenticationType = AuthenticationTypes.Secure; try { DirectorySearcher searcher = new DirectorySearcher(AD); searcher.Filter = String.Format( " (&(objectClass=user)(samAccountName={0})) " , UserName); System.DirectoryServices.SearchResult result = searcher.FindOne(); if (result != null ) { DirectoryEntry userEntry = result.GetDirectoryEntry(); if (userEntry != null ) { try { userEntry.Invoke( " ChangePassword " , new Object[] { OldPassWord, NewPassWord }); userEntry.CommitChanges(); userEntry.Close(); ViewData[ " Msg " ] = " 修改密码成功! " ; } catch (Exception ex) { ViewData[ " Msg " ] = " 操作失败,错误原因: " + ex.ToString(); } } } else { ViewData[ " Msg " ] = " 操作失败,未知账号或密码错误! " ; } AD.Close(); } catch (Exception ex) { ViewData[ " Msg " ] = " 操作失败,错误原因: " + ex.ToString(); } return View(); }