ASP.NET Kernel ID Does Not Use UserManager <ApplicationUser>

I have an old asp.net base identity database and I want to map it to a new project (web api).

For the test only, I copied the Models folder and the ApplicationUser file from the previous project (ApplicationUser just inherits from IdentityUser, no changes at all) - making DB first seems like a bad idea.

I am registering Identity with ConfigureServices (but I am not adding it to the pipeline since my only intention is to use the UserStore)

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

I expect now

     UserManager<ApplicationUser>

... should be automatically entered into the constructors.

However, when adding the following code to the controller, the private UserManager _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

... api : HttpRequestException: : 500 ( ).

"" web api, .

, , - . , ?

P.S. " " :

: 'System.InvalidOperationException'
Microsoft.Extensions.DependencyInjection.dll

: 'Namespace.Data.ApplicationDbContext' "Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4 [Namespace.Models. ApplicationUser, Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole, Namespace.Data.ApplicationDbContext, System.String].

+4
3

app.UseIdentity(); Configure:

 public void Configure(IApplicationBuilder app, 
                       IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        /*...*/
        app.UseIdentity();
       /*...*/          
    }

  services.AddIdentity<ApplicationUser, IdentityRole>()?

 public void ConfigureServices(IServiceCollection services)
 {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

 }

. , ApplicationDbContext IdentityDbContext.

+4

DI .

services.AddTransient<UserManager<ApplicationUser>>();
services.AddTransient<ApplicationDbContext>();

+2
public void ConfigureServices(IServiceCollection services){
...
var identityBuilder = services.AddIdentityCore<ApplicationUser>(user =>
            {
                // configure identity options
                user.Password.RequireDigit = true;
                user.Password.RequireLowercase = false;
                user.Password.RequireUppercase = false;
                user.Password.RequireNonAlphanumeric = false;
                user.Password.RequiredLength = 6;
            });
            identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services);
            identityBuilder.AddEntityFrameworkStores<DbContext>().AddDefaultTokenProviders();
    ...
}
0
source

Source: https://habr.com/ru/post/1666923/


All Articles