是否可以使用会员 API 更改用户名

发布于 2024-07-23 17:11:20 字数 154 浏览 10 评论 0 原文

我正在 ASP.NET 中使用默认的 sql 成员资格提供程序,并且我想提供一个页面来更改用户的用户名。 我相信我确信我可以使用自定义提供程序来完成此操作,但是可以使用默认提供程序来完成此操作吗?

我的问题的第二部分是: 我是否应该允许用户在创建帐户后更改用户名?

I am using the default sql membership provider with ASP.NET and I would like to provide a page to change the user's username. I believe I am sure I could do this with a custom provider, but can this be done with the default provider?

Second part of my question is:
Should I allow users to change their username after the account is created?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

猫卆 2024-07-30 17:11:20

确实,默认的 SQL 成员身份提供程序不允许更改用户名。 但是,如果您的网站上有有效的参数允许用户更改用户名,则没有内在原因阻止用户更改用户名。 SQL数据库中的所有表都没有用户名作为键,一切都基于用户的ID,因此从实现的角度来看,这将相当容易。

It's true that the default SQL Membership Provider does not allow username changes. However, there's no intrinsic reason to prevent users from changing their usernames if you have a valid argument, on your site, to allow it. None of the tables in the SQL database have the username as a key, everything is based on the user's ID, so from an implementation perspective it would be fairly easy.

凤舞天涯 2024-07-30 17:11:20

如果您使用 SqlMembershipProvider,您可以扩展它 - 它也与 这个问题
Roadkill 是一个 wiki 引擎,而不是我的编码风格的描述。

using System;
using System.Web.Security;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

namespace Roadkill.Core
{
    public class RoadkillMembershipProvider : SqlMembershipProvider
    {
        private string _connectionString;

        protected string ConnectionString
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                    MembershipSection section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
                    string defaultProvider = section.DefaultProvider;
                    string connstringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();
                    _connectionString = config.ConnectionStrings.ConnectionStrings[connstringName].ConnectionString;
                }

                return _connectionString;
            }
        }

        public bool ChangeUsername(string oldUsername, string newUsername)
        {
            if (string.IsNullOrWhiteSpace(oldUsername))
                throw new ArgumentNullException("oldUsername cannot be null or empty");

            if (string.IsNullOrWhiteSpace(newUsername))
                throw new ArgumentNullException("newUsername cannot be null or empty");

            if (oldUsername == newUsername)
                return true;

            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();

                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandText = "UPDATE aspnet_Users SET UserName=@NewUsername,LoweredUserName=@LoweredNewUsername WHERE UserName=@OldUsername";

                    SqlParameter parameter = new SqlParameter("@OldUsername", SqlDbType.VarChar);
                    parameter.Value = oldUsername;
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@NewUsername", SqlDbType.VarChar);
                    parameter.Value = newUsername;
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@LoweredNewUsername", SqlDbType.VarChar);
                    parameter.Value = newUsername.ToLower();
                    command.Parameters.Add(parameter);

                    return command.ExecuteNonQuery() > 0;
                }
            }
        }
    }
}

If you use SqlMembershipProvider, you can extend it - it also relates to this question.
Roadkill is a wiki engine not a description of my coding style.

using System;
using System.Web.Security;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

namespace Roadkill.Core
{
    public class RoadkillMembershipProvider : SqlMembershipProvider
    {
        private string _connectionString;

        protected string ConnectionString
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                    MembershipSection section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
                    string defaultProvider = section.DefaultProvider;
                    string connstringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();
                    _connectionString = config.ConnectionStrings.ConnectionStrings[connstringName].ConnectionString;
                }

                return _connectionString;
            }
        }

        public bool ChangeUsername(string oldUsername, string newUsername)
        {
            if (string.IsNullOrWhiteSpace(oldUsername))
                throw new ArgumentNullException("oldUsername cannot be null or empty");

            if (string.IsNullOrWhiteSpace(newUsername))
                throw new ArgumentNullException("newUsername cannot be null or empty");

            if (oldUsername == newUsername)
                return true;

            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();

                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandText = "UPDATE aspnet_Users SET UserName=@NewUsername,LoweredUserName=@LoweredNewUsername WHERE UserName=@OldUsername";

                    SqlParameter parameter = new SqlParameter("@OldUsername", SqlDbType.VarChar);
                    parameter.Value = oldUsername;
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@NewUsername", SqlDbType.VarChar);
                    parameter.Value = newUsername;
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@LoweredNewUsername", SqlDbType.VarChar);
                    parameter.Value = newUsername.ToLower();
                    command.Parameters.Add(parameter);

                    return command.ExecuteNonQuery() > 0;
                }
            }
        }
    }
}
溇涏 2024-07-30 17:11:20

Scott Mitchell 有一篇很棒的文章描述了如何处理这种情况:https://web.archive.org/web/20210927191559/http://www.4guysfromrolla.com/articles/070109-1.aspx

他文章中的重要引用:

不幸的是,理想主义和实用主义很少有交叉。 在某些情况下(例如允许用户更改用户名),我们别无选择,只能直接使用底层数据存储。

他还展示了如何在更改用户名/电子邮件后重新对用户进行身份验证。

Scott Mitchell has a great article describing how to handle this situation here: https://web.archive.org/web/20210927191559/http://www.4guysfromrolla.com/articles/070109-1.aspx

Important quote from his article:

Unfortunately, idealism and pragmatism only rarely intersect. In some cases - such as allowing a user to change their username - we have no choice but to work directly with the underlying data store.

He also shows how to re-authenticate the user after changing their username/email.

空城缀染半城烟沙 2024-07-30 17:11:20

如果您想使用会员 API 来做到这一点,正确的方法似乎是这样的:

http://omaralzabir.com /how_to_change_user_name_in_asp_net_2_0_membership_provider/

基本上,您必须执行以下操作(为了完整起见,我从上面的链接复制):

  1. 使用新电子邮件地址创建新用户
  2. 获取旧帐户的密码并将其设置为新账户。 如果您无法通过会员提供商获取旧密码,请询问用户。
  3. 为新用户帐户创建新配置文件
  4. 将旧配置文件中的所有属性复制到新配置文件对象。
  5. 从旧帐户中注销用户
  6. 自动登录到新帐户,这样用户就不会注意到刚刚发生了什么令人难以置信的事情。

If you want to do that with the Membership API, it seems the right way would be like this:

http://omaralzabir.com/how_to_change_user_name_in_asp_net_2_0_membership_provider/

Basically, you have to do the following (I copied from the above link, for sake of completeness):

  1. Create a new user using the new email address
  2. Get the password of the old account and set it to the new account. If you can’t get the old password via Membership provider, then ask user.
  3. Create a new profile for the new user account
  4. Copy all the properties from the old profile to the new profile object.
  5. Log out user from old account
  6. Auto sign in to the new account so that user does not notice what an incredible thing just happened.
╰沐子 2024-07-30 17:11:20

由于 Membershiop API 不允许直接修改用户名,因此您可以直接访问数据库中的 aspnet_Membership 表。

Since Membershiop API does not allow username modification directly, you can access directly the aspnet_Membership table in your database.

多情出卖 2024-07-30 17:11:20

这是一个包含企业库 DAB 和其他一些细微更改的版本。 另外,我认为返回布尔值没有意义,因为它要么成功,要么抛出异常。

        public static void ChangeUsername(string oldUsername, string newUsername)
    {
        if (string.IsNullOrWhiteSpace(oldUsername))
        {
            throw new ArgumentNullException("oldUsername cannot be null or empty");
        }

        if (string.IsNullOrWhiteSpace(newUsername))
        {
            throw new ArgumentNullException("newUsername cannot be null or empty");
        }

        if (oldUsername.Equals(newUsername))
        {
            return;
        }

        Database db = DatabaseFactory.CreateDatabase();
        using (DbCommand cmd = db.GetSqlStringCommand("UPDATE dbo.aspnet_Users SET UserName=@NewUsername, LoweredUserName=@LoweredNewUsername WHERE UserName=@OldUsername"))
        {
            db.AddInParameter(cmd, "@OldUsername", DbType.String, oldUsername);
            db.AddInParameter(cmd, "@NewUsername", DbType.String, newUsername);
            db.AddInParameter(cmd, "@LoweredNewUsername", DbType.String, newUsername.ToLower());

            db.ExecuteNonQuery(cmd);                
        }
    }

Here's a version that incorporates the Enterprise Libraries DAB and a couple other minor changes. Also, I don't see a point in returning a Boolean, since it's either going succeed or throw an exception.

        public static void ChangeUsername(string oldUsername, string newUsername)
    {
        if (string.IsNullOrWhiteSpace(oldUsername))
        {
            throw new ArgumentNullException("oldUsername cannot be null or empty");
        }

        if (string.IsNullOrWhiteSpace(newUsername))
        {
            throw new ArgumentNullException("newUsername cannot be null or empty");
        }

        if (oldUsername.Equals(newUsername))
        {
            return;
        }

        Database db = DatabaseFactory.CreateDatabase();
        using (DbCommand cmd = db.GetSqlStringCommand("UPDATE dbo.aspnet_Users SET UserName=@NewUsername, LoweredUserName=@LoweredNewUsername WHERE UserName=@OldUsername"))
        {
            db.AddInParameter(cmd, "@OldUsername", DbType.String, oldUsername);
            db.AddInParameter(cmd, "@NewUsername", DbType.String, newUsername);
            db.AddInParameter(cmd, "@LoweredNewUsername", DbType.String, newUsername.ToLower());

            db.ExecuteNonQuery(cmd);                
        }
    }
小嗲 2024-07-30 17:11:20

不可以,MembershipUser 类不允许修改 Username 属性,因此您无法执行此操作。

实际上,您不应该允许更改用户名。 如果你允许以某种方式这样做,那么它将失去其目的和性质。

No, the MembershipUser class does not allow to modify the Username property so you cannot do it.

Practically you should not allow the username to change. If you allow to do so somehow then it will lose its purpose and nature.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文