Oleg Potkin Oleg Potkin - 2 months ago 36
C# Question

How to create new user accounts from another (admin role) account in ASP.NET MVC 5 (Identity)

I have an account with admin role and I need to create functionality for management (CRUD) of user accounts (set email, password, role and some other parameters from, for example, Admin user account) via the web interface.
Which way is the most suitable for this?

Answer

You can use built in UserManager<TUser,TKey> to programmatically create users and add them to a particular role.

For example:

var user = new ApplicationUser {
    UserName = "new_user",
    Email = "user@gmail.com"
};
string password = "secret";

using (var db = new ApplicationDbContext())
{
    var store = new UserStore<ApplicationUser>(db);
    var manager = new UserManager<ApplicationUser, string>(store);

    var result = manager.Create(user, password);
    if (!result.Succeeded)
        throw new ApplicationException("Unable to create a user.");

    result = manager.AddToRole(user.Id, "Administrator");
    if (!result.Succeeded)
        throw new ApplicationException("Unable to add user to a role.");
}