45

Edit: This question is outdated

The Identity Framework was a moving target at the moment I asked this. The authors changed quite a few things and they have decoupled several others, making everything easier.

Have a look at the Asp.NET Identity Sample project on github.


I'm creating a small application that requires user management. Registration is not allowed, instead there is a super user that will create and modify login information.

I'm using the new ASP.NET Identity membership system, and sure enough, creating users and adding roles is easy and intuitive.

Now, my question: How to obtain a list of users using the AuthenticationIdentityManager class that is used by the generated AccountController class? I couldn't find a way to access the user list from my controller.

(By the way, the new name "Identity" may sound awesome to some people but it is a pain to search for.)

Edit: If I try to do this

ApplicationDbContext UsersContext = new ApplicationDbContext();
UsersContext.Users.ToList(); // Exception

I get an exception Invalid column name 'Discriminator'. The definition of ApplicationDbContext is generated automatically by the new application wizard:

using Microsoft.AspNet.Identity.EntityFramework;

namespace Cobranzas.Models
{
    public class ApplicationUser : User
    {

    }
    public class ApplicationDbContext : IdentityDbContextWithCustomUser<ApplicationUser>
    {

    }
}

So my guess is that Discriminator column is for telling apart ApplicationUser from User. However, it does not exists in my database (which was created automatically by the application.)

Leonardo Herrera
  • 8,388
  • 5
  • 36
  • 66
  • 1
    Have you looked at the sample application? https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample – sam Sep 12 '13 at 21:20
  • 2
    There is nothing there to get a list of users. I already have a working application, I just need a list of all users. – Leonardo Herrera Sep 12 '13 at 21:29

6 Answers6

31

I found out that I wasn't using the derived ApplicationUser object for anything, so I just went ahead and changed all uses of it for plain old User. Then I just changed ApplicationDbContext definition for the following:

public class ApplicationDbContext : IdentityDbContext<
    User, UserClaim, UserSecret, UserLogin,
    Role, UserRole, Token, UserManagement>
{
}

And now I can access the user list:

UsersContext = new ApplicationDbContext();
...
UsersContext.Users.ToList();

However, I think this will come back and haunt me in the future (I'll probably need to add more fields to User) so probably I'll have to use the same approach as in this question:

Get all role names in ASP.NET MVC5 Identity system

Edit: Since I got the need to add a new property, I had to revert my changes. So I went ahead and did a line by line comparison with the ASP.NET Identity Sample Project, and found out that the generated project had the following line:

IdentityManager = new AuthenticationIdentityManager(new IdentityStore());

while the Sample application had included the database context in the constructor. So I added it in my constructor, recreated the database and the problem went away.

IdentityManager = new AuthenticationIdentityManager(new IdentityStore(new ApplicationDbContext()));
Community
  • 1
  • 1
Leonardo Herrera
  • 8,388
  • 5
  • 36
  • 66
  • This got me as well. I do not understand at all why the included VS2013 RTM template is configured this way. Could there possibly be a reason or is this an oversight? – joelmdev Nov 05 '13 at 19:48
  • And wait to see what's up when you update the RTM versions with the 1.0 ones. Everything was changed; fortunately, the sample application was also changed to reflect this. – Leonardo Herrera Nov 05 '13 at 20:10
  • You mean RC to RTM? are you referring to this sample app? https://github.com/rustd/AspnetIdentitySample – joelmdev Nov 05 '13 at 20:16
  • Yeah, that's it. Take a look at [this commit](https://github.com/rustd/AspnetIdentitySample/commit/776680f37657affff109a1107c90cde4963d2eb2#diff-eb7df5aa8f2b1fb32e562813c8c4e650) - I had to change my application to fit the new architecture. It took me a couple of hours but it seems to be working fine. – Leonardo Herrera Nov 05 '13 at 20:21
  • 1
    You just saved my bacon! I've been trying to use MembershipUserCollection users = Membership.GetAllUsers(), but it kept returning nothing, even with users in my table. My app is using ASP.NET Identity, so Membership is probably accessing a deprecated table with no users. I already had the context set up, so literally all I had to do was take your lead and invoke the context, grab its users, and cast to a list. BOOM! It's working beautifully. After looking a 20+ S.O. pages, I'm glad I held out for this one. Thanks! – midoriha_senpai Apr 20 '17 at 22:57
17
  1. Create ASP .NET MVC5 project by default
  2. Create ASP .NET Identity tables properly and change connection string as well.
  3. To get users just do the following test A. Go to AccountController B. Create any dummy method and put there
var context = new ApplicationDbContext();

var allUsers = context.Users.ToList();

enter image description here

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • Thank you. Please consider that this question is outdated. [This comment](http://stackoverflow.com/questions/18773838/how-to-obtain-a-list-of-users-from-asp-net-identity/20954972?noredirect=1#comment31171316_18833772) may be of interest. – Leonardo Herrera Jan 06 '14 at 20:46
4

For RTM, you will have to drop down to your DbContext or whatever your specific store implementation has to enumerate all users. In the next release, we will most likely be adding an optional IQueryable Users/Roles method on the Manager classes that stores can implement to expose IQueryables for both users and stores.

Dr Rob Lang
  • 6,659
  • 5
  • 40
  • 60
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • Thank you. Right now I'm using `IEnumerable rolesForUser = await IdentityManager.Store.Roles.GetRolesForUserAsync(user.Id, CancellationToken.None);` which smells funny to my untrained nose. – Leonardo Herrera Sep 16 '13 at 17:26
  • It will be great to have methods to Delete(remove) in addition to the IQueryable Users/Roles methods you mention. Now UserManger Delete user method is lacking. – subsci Dec 22 '13 at 07:28
  • 5
    These are available now in the 2.0-alpha1 release – Hao Kung Dec 27 '13 at 00:56
2
using System.Linq;
using System.Data;
using System.Data.Entity;

        var db = new ApplicationDbContext();
        var Users = db.Users.Include(u => u.Roles);
Hossein Hajizadeh
  • 1,357
  • 19
  • 10
0

If we can use the following type of Constructor in Identity AccountController.

public AccountController(ApplicationUserManager userManager,
            ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
      UserManager = userManager;
      AccessTokenFormat = accessTokenFormat;
}

public ApplicationUserManager UserManager
{
     get
     {
          return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
     }
     private set
     {
          _userManager = value;
     }
}

then we can directly used UserManager object to get user list like

var userList= UserManager.Users.ToList();
Unheilig
  • 16,196
  • 193
  • 68
  • 98
0

You can do this by explicitly setting right types:

var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
IQueryable<IdentityUser> usersQuery = userManager.Users;
List<IdentityUser> users = usersQuery.ToList();

Imoports:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Linq;
using System.Collections.Generic;