How to check user role in MVC 5 identity?

2019-08-15 05:19发布

I create a EF code first database identity system with custom roles. When i register a user i put him in a role, and in the database i can see that works on the AspNetUserRoles table.

But when i try to check the user role using User.IsInRole("admin") i.e, it always return false( i tried with low, upper, all the way case). I need to put something in the webconfig? Or what im missing here? Its my first time developing with this new Identity system and i think that is a bit confuse.

In my immediate window:

User.Identity.Name
"teste06"
User.Identity.IsAuthenticated
true
User.IsInRole("admin")
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in     System.Data.dll

Exception:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

2条回答
等我变得足够好
2楼-- · 2019-08-15 05:44

It seems that the role Manager Is Activated and it is trying to create an SQL Express Database to validate roles, i 've had the same issue i solve it by adding this code to my web.config file

<system.webServer>
  <modules>
    <remove name="RoleManager" />
  </modules>
</system.webServer>
查看更多
时光不老,我们不散
3楼-- · 2019-08-15 05:49

You have to make sure you have this in your startup class

app.UseSignInCookies();

Also, I'm guessing your DbContext class is derived from IdentityDbContext<ApplicationUser>or IdentityDbContext.

If not, make sure you do.

Look this article for reference.

Similar post relating to your problem can be found here

查看更多
登录 后发表回答