0

I try to access usermanager in order to find a user. But struggling to figure out how this should be done. Here is what I have so far:

ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(AppDomain.CurrentDomain.BaseDirectory + "appsettings.json")
            .Build();

        var connectionString = configuration.GetConnectionString("AppDb");
        optionsBuilder.UseSqlServer(connectionString);
    }
}

Program.cs:

var connectionString = builder.Configuration.GetConnectionString("AppDb");
builder.Services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString));

LoginController:

public class LoginController : Controller
{
    private readonly UserManager<IdentityUser> _userManager;

    public LoginController(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    public IActionResult Index()
    {
        var user = _userManager.FindByEmailAsync("user@home.se");
        //return View();
        return null;
    }
}

I get an error in LoginController when initiate the LoginController:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'WebSite.Controllers.LoginController'.

What am I doing wrong here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MTplus
  • 2,077
  • 4
  • 34
  • 51
  • Can you show where you are registering the identity service? – JHBonarius Nov 02 '22 at 12:39
  • I think there was the same problem: https://stackoverflow.com/questions/41679217/asp-net-core-identity-does-not-inject-usermanagerapplicationuser – BeSter Development Nov 02 '22 at 12:41
  • @JHBonarius this is the only code I have so far.... Can you show me what I need to add? – MTplus Nov 02 '22 at 12:46
  • ??Are you just trying random code snippets you find? Maybe you should start looking for good guides. E.g. Microsoft has very good documentation nowadays: [link](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity). – JHBonarius Nov 02 '22 at 13:15
  • You also might want to read how to add EFCore to ASP.Net [here](https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-6.0). You don't need call configurationbuilder in ASP.net if you're doing it right. – JHBonarius Nov 02 '22 at 13:18

1 Answers1

0

I think that u r missing in Program.cs:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

and then u can configure options

builder.Services.Configure<IdentityOptions>(options =>
{
    // Password settings.
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;

    // Lockout settings.
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.AllowedForNewUsers = true;

    // User settings.
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
});

and

app.UseIdentity();
J.Memisevic
  • 429
  • 4
  • 11
  • It worked if i added builder.Services.AddIdentityCore().AddEntityFrameworkStores(); I was not able to add app.UseIdentity(); program.cs could not resolve that.. – MTplus Nov 02 '22 at 14:16