2

我有一个 ASP.NET 网站,它将使用 Active Directory 来存储用户。要求允许用户使用他们的电子邮件作为用户名。Active Directory 不允许在用户名中使用像“@”这样的字符。我创建了一个类来扩展 ActiveDirectoryMembershipProvider;它在调用基类函数之前将用户名从 (user@domain.com 转换为 user_x0040_domain.com )。例子:

  public override bool ValidateUser(string username, string password)
        {
            string encodedUsername = this.Encode(username);
            return base.ValidateUser(encodedUsername, password);
        }

问题是在 MembershipUser 中不允许更改用户名。如何处理覆盖返回 MembershipUser 的方法?Like MembershipUser GetUser(string username, bool userIsOnline)

4

1 回答 1

1

我想您可以覆盖 Active Directory 提供程序返回的 MembershipUser,如下所示:

public class MyActiveDirectoryMembershipProvider : ActiveDirectoryMembershipProvider
{
    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    {
        ActiveDirectoryMembershipUser user = (ActiveDirectoryMembershipUser)base.GetUser(providerUserKey, userIsOnline);
        if (user == null)
            return null;

        return new MyActiveDirectoryMembershipUser(user);
    }

    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        MembershipUserCollection newColl = new MembershipUserCollection();
        foreach (ActiveDirectoryMembershipUser user in base.FindUsersByName(usernameToMatch, pageIndex, pageSize, out totalRecords))
        {
            newColl.Add(new MyActiveDirectoryMembershipUser(user));
        }
        return newColl;
    }

    // TODO: check other methods to override
}

public class MyActiveDirectoryMembershipUser : ActiveDirectoryMembershipUser
{
    private string _userName;

    public override string UserName
    {
        get
        {
            return _userName;
        }
    }

    public MyActiveDirectoryMembershipUser(ActiveDirectoryMembershipUser user)
    {
        // TODO: do your decoding stuff here
        _userName = MyDecode(user.Email);
    }
}

注意:您需要确保所有返回用户的方法都被覆盖。它还对收集方法有一些性能影响,因为您需要复制收集(如我在示例中所示)。

于 2011-11-13T07:13:39.023 回答