How to use Roles in ASP.NET Core 2.1?

后端 未结 5 2242
小蘑菇
小蘑菇 2021-02-12 20:31

I\'ve created a test project using:

dotnet new razor --auth Individual --output Test

This creates a Startup.cs that contains:

p         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-12 20:45

    Starting in .Net Core 2.1, AddDefaultIdentity is the same as calling:

    • AddIdentity
    • AddDefaultUI
    • AddDefaultTokenProviders

    To add role functionality, go to Startup.cs under ConfigureServices you can use .AddRoles like so:

    services.AddDefaultIdentity()
        .AddRoles()            //<-- This line
        .AddEntityFrameworkStores();
    

    That's all that is needed. It is crucial to logout and login again.

    For the record (and just to test), I tried services.AddIdentity:

    IServiceCollection does not contain a defintion for 'AddIdentity'...

    and services.AddIdentityCore (no error until Debug and displaying the page):

    InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).

    There may be more you can do to get the latter two working, but the code I posted for AddDefaultIdentity is all I needed in order to get User.IsInRole and other role functionality working in .NET Core 2.1 (and 3.1).

提交回复
热议问题