首页 > 解决方案 > 创建具有唯一用户名的新 AD 用户

问题描述

我有一个 Web 视图,它采用一个人的名字和姓氏,并尝试使用名字的第一个字母 + 姓氏的命名上下文在活动目录中创建一个新用户。这很好用,但是当创建多个具有相同姓氏和名字且以相同字符开头的用户时(即,Andy Gordan => agordan | Alex Gordan => agordan),会抛出错误,因为已经有相同用户名的用户存在。

如何在下方添加 if/else 语句,检查活动目录以查看用户名是否已存在,如果存在,则在名字后添加中间首字母(Alex M Gordan => agordan,下一个用户输入:Andy M Gordan = > 安戈尔丹)。

[HttpPost]
public ActionResult Index(CreateUser model)
{
    //Domain name
    var domainName = "XXX";
    //Fully distinguished name of OU to create user in
    var location = model.Location;
    var userOU = "OU=" + location + ",OU=XXX,DC=XXX,DC=com"; 

    using (var pc = new PrincipalContext(ContextType.Domain, domainName, userOU))
    {
        using (var up = new UserPrincipal(pc))
        {
            //Creates username and display name from firstname and lastname
            **var userName = model.FirstName[0].ToString().ToLower() + model.LastName.ToString().ToLower();**

            var displayName = model.FirstName + " " + model.LastName;
            var password = "XXX";

            up.Name = displayName;
            up.DisplayName = displayName;
            up.GivenName = model.FirstName;
            up.MiddleName = model.MiddleI;
            up.Surname = model.LastName;
            up.SamAccountName = userName;
            up.EmailAddress = userName + "@XXX.com";
            up.UserPrincipalName = userName + "@XXX.com";
            up.SetPassword(password);
            up.Enabled = true;
            up.ExpirePasswordNow();

            try
            {
                //Attempt to save the account to AD
                up.Save();
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Exception creating user object. " + e);
                return View(model);
            }

            //Set department to add
            DirectoryEntry entry = up.GetUnderlyingObject() as DirectoryEntry;

            //DirectoryEntry group = entry.Children.Add("CN="+ )
            entry.Properties["department"].Value = model.Department;
            //entry.Properties["member"].Add(up);
            try
            {
                //try and commit the changes
                entry.CommitChanges();
            }
            catch(Exception e)
            {
                ModelState.AddModelError("", "Exception adding department. " + e);
                return View(model);
            }
        }
    }

    //Redirect to completed page if successful
    return RedirectToAction("Completed");

}//POST Index

标签: c#asp.net-mvcactive-directorydirectoryservicesprincipalcontext

解决方案


推荐阅读