範例程式碼為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();
}