Search code examples
c#asp.netasp.net-identity

ASP.NET MVC SQL Server not accesable when trying to authenticate or access roles?


When I try to use Roles.IsUserInRole("roleX") or any related method I get a database connection issue, as can be seen here. I can access roles in the database and read/write any time before this, so I am quite sure I do not have any connection issues. All users role ID's match fine. The error also happens when trying to access a controller method that is authenticated to a certain role? Once any line relating to role checking is hit the app instantly locks up and errors out after about a minute. The only time I ever get this error is when trying to access roles, not sure if somehow identity is not connecting to the DB? I am at a total loss on this issue, the only thing I can think of is that something with Identity is not set up right. Any ideas are greatly appreciated.


Solution

  • Your problem is that Roles.IsUserInRole("roleX") is not part of Identity framework. This is part of MembershipProvider and you don't want to use it. Reason for getting this error - MembershipProvider tries to be helpful and attempts connecting to a database, a database you never told it about.

    If you need to check if current user is in a role use User.IsInRole("RoleX");. Where User is part of a Controller or a View. Or you can also do it via HttpContext.Current.User.IsInRole("RoleX"); This checks the auth cookie for information about roles (all the roles for logged in user are persisted in auth cookie).

    If you would like to dip into database to check for roles for an arbitrary user (not the currently logged in one) - you need to use ApplicationUserManager.IsInRoleAsync()