Similar Posts

Leave a Reply

Your email address will not be published.

142 Comments

  1. Hi,
    I am facing an error in source code when adding a new role.

    [HttpPost]
    public async Task AddRole(string roleName)
    {

    await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
    return RedirectToAction(“Index”);
    }

    here I got roleName as a null value.

    1. Hi, Only If the Textbox is empty, It throws a null object error. Else it works fine. Have tested it right now. However, I will add a null check to handle the null issue too. Thanks for letting me know.
      Regards

      1. Hi,

        thank you for replay. that’s my mistake.

        can you please do a sample app in the oracle DB with Identity and sample architecture of repository pattern without entity framework.

  2. What if I want a list of users in an specific role as an iQueryable, so I can create a PaginatedList?

  3. Very good tutorial.
    Thanks a lot, Mukesh

    But, in UserRolesController, I have had to add .ToList()

    foreach (var role in _roleManager.Roles.ToList())

    1. Can you check if _userManager is null? If that’s the case you must have missed out the constructor dependency injection or at the Startup.Or else , there might be no users available. Let me know
      Regards

  4. So far really helpful!
    I am up to the part of trying to seed default users and I am getting an error with CreateHostBuilder. I’ve directly copy pasted your code and it is saying “the name CreateHostBuilder does not exist in the current context”. I am using .NET Core 3.1 and have copied the tutorial identically to this point.
    Basically what I am trying to achieve is exactly what you have done, although I would like to have another section to the user configuration where access is restricted to a store (pretty much identical to roles).

      1. Thanks Mukesh for your help, I have found where the problem was in my code. And have completed the tutorial.
        I am now trying to restrict access to certain views and buttons (rather than just the controller) – is this possible?

        1. Yes, you can use the Policy option to control the views

          https://docs.microsoft.com/en-us/aspnet/core/security/authorization/views?view=aspnetcore-5.0

          Something below what I did for creating Policy based on the Roles (you can use multiple roles though to define policy):
          Startup.cs
          ConfigureServices method

          add below line
          services.AddAuthorizationCore(options =>
          {
          options.AddPolicy(“SuperAdminOnly”, policy => policy.RequireRole(“SuperAdmin”));
          options.AddPolicy(“AdminOnly”, policy => policy.RequireRole(“Admin”));
          });

          Then in the Views,
          added
          @using Microsoft.AspNetCore.Authorization
          @inject IAuthorizationService AuthorizationService

          @if ((await AuthorizationService.AuthorizeAsync(User, “SuperAdmin”)).Succeeded)
          {
          This text is only visible for user with SuperAdmin policy
          }

  5. InvalidOperationException: There is already an open DataReader associated with this Connection which must be closed first.
    it error on here.
    if( await _userManager.IsInRoleAsync(user, role.Name))

    please help brother

    1. Problem is the foreach is looping over the roles like this:
      foreach (var role in _roleManager.Roles)
      Because this is an IQuerable the DataReaders connection will stay open until each role has been read.
      Solution:
      foreach (var role in _roleManager.Roles.ToList())
      This way all the roles are loaded.

  6. Ctrl + Shift + h
    ApplicationUser
    Models.ApplicationUser

    Entire solution

    *.cshtml.cs
    This is in order to update all Pages simultaneously

  7. I have followed your guide and can’t find any mistakes, however, I am getting a System.InvalidOperationException: ‘Scheme already exists: Identity.Application, in Program.cs on host.Run().

    Comparing my files with that on your Github Repo I am unable to find a mistake… Any suggestions?

    1. in the manage View, you should change the
      asp-action=”EditUser” to asp-action=”Index”

      in the cancel button and it will work.

  8. Hi, what a nice and in-depth article. I am working on a Razor application, and so far I have been able to apply all the concepts in my application. However, I can’t seem to get the “Addings Users to Roles” to work. Do you by any means know how to apply this in razor? Thanks

  9. I check you hero boiletplate.
    there is permission level of user role.
    Can you show how does it work?

  10. Very thorough tutorial! Thank you very much!
    I am having an issue with the database which is always adding a Identity.AspNetUsers table in addition to the other (renamed) tables.
    This table is where the data goes when a user registers. It appears that this table is generated when a user registers if it is not present.
    Do you have any insight on this problem.

    Thanks,!

  11. Hello,
    This tutorial looks quite useful but I think you should give more information about paths hwere to insert code. For example, I’m at the point where you ask me to insert an Enum. But where? In the models folder? In an existing class?

    Keep up the good work and I’m waiting for your answer.

        1. S/he probably ran into a brain-freeze like I did.. until I (had coffee, and) realised that I needed to *create a new Enums.cs class under the Data folder*

  12. In order to search for all*** occurrences of IdentityUser and replaced with Application user: press CTRL + , .
    *** It’s not perfect, since it got me some troubles, described below.
    If you find the following error:
    No service for type ‘Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]’ has been registered
    In means one file is asking for a service of type IdentityUser instead of ApplicationUser.
    So you have to search throughtout the files, and see which miss the ApplicationUser replacement.
    In my case was a partial view: _ManageNav.cshtml. But other users have found that it can also occured with: _LoginPartial.cshtml
    You can find more information here:
    https://stackoverflow.com/questions/52568264/no-service-for-type-microsoft-aspnetcore-identity-usermanager1microsoft-aspne

    1. On the _ManageNav.cshtml file make sure you have the following:
      @using PROJECTNAME.Models
      @using Microsoft.AspNetCore.Identity
      @inject SignInManager SignInManager

  13. in the tutorial, when modifying table names you have the code line 5 I believe, builder.Entity(entity =>…
    in your code on Github it is (line21) builder.Entity(entity => …

    Which is correct?

  14. Mukesh, you forgot to mention in Adding Custom Fields To Identity User section :
    Edit the following line of code inside OnModelCreating() method in ApplicationDbContext, :
    From this
    builder.Entity(entity =>
    {
    entity.ToTable(name: “User”);
    });
    to
    builder.Entity(entity =>
    {
    entity.ToTable(name: “User”);
    });
    Because entity framework create a new Identity.AspNetUsers table instead of using Identity.User when we add a new migration .

    1. Hi,
      I think you want to say replace:
      builder.Entity(entity =>
      {
      entity.ToTable(name: “User”);
      });
      to:
      builder.Entity(entity =>
      {
      entity.ToTable(name: “User”);
      });

  15. Dude, you’re amazing for sharing this free content, i hope you get more attention, better than Udemy or YouTube tutorials.

  16. Great tutorial sir.
    If I have another entity in the project such as car entity how can I create the table car without identity.car.

    Thanks.

  17. I can confirm that the table “Identity.AspNetUsers” still gets created, I believe it should not be created according with the instructions.
    Your guide is excellent!!!

  18. ArgumentException: Value cannot be null or empty. (Parameter ‘normalizedRoleName’)

    79. if (await _userManager.IsInRoleAsync(user, role.Name))

    I get this exception while clicking on Manage Roles. What should I do?

    1. Hi, I would suggest you check out your database table first, especially where you store the identity roles. Ensure the normalized role name column isn’t empty. If it’s empty, then the way you are inserting the roles to your table has an issue. That should be fixing it.

      Regards

  19. This article is splendid. Unlike most other articles on the internet, the author has explained everything to the point very clearly. Thank you very much for your genuine effort.

    Excellent Job.

  20. Okay. I made the mistake of adding this to an existing project. A couple of things are not happening. First, when I tried to use my already existing Context class, the wizard would not continue. It forced me to create a new Context class. Second, no migration code was created.

    Any ideas on what I need to do to rectify this?

    This is a pretty slick tutorial. I’m still working my way through it, but it is very thorough and I think it is everything I need. Once I get past these initial issues, I think it’ll fly along.

    1. I’ve been doing some digging, and there are some additional issues, and a possible reason. I created an app from scratch, and added all of the Identity classes. However, the dialog allowing me to add the source code never comes up. So I don’t see any code in the project. And in digging further into the original project that I modified, I noticed that none of the Identity Model classes were created. Which is why I think there was no migration code created. Makes sense.

      Okay. The reason I think this is happening is that I am using Visual Studio 2019, Not Visual Studio Code. The dialogs in the creation wizard are distinctly different looking, and like I said–there is no opportunity to have the Identity source code added to the project.

      I’m going to bite the bullet and download VS Code tonight and mess around. I’m hoping that I can get something hashed together. I’ll keep you posted. And if you have any insights or suggestions, please don’t hesitate to let me know.

        1. Yeah. It’s not about VS Code.

          I’m running VS 2019 Enterprise. The dialogs are definitely different looking. Very odd.

          I’ve downloaded your source. I’m going to attack this from that angle, just so I can see the completed project and how it runs.

        2. Okay. I took a couple days off for Mother’s Day and weekend stuff. I’m making progress. But I’m running into a table naming issue. When I generate the table update migration code, the following appears:

          modelBuilder.Entity(“MapItGo_Web_App.Models.ApplicationUser”, b =>
          {
          b.Property(“Id”)
          .HasColumnType(“nvarchar(450)”);
          .
          .
          .
          b.ToTable(“AspNetUsers”);
          });

          Where is “AspNetUsers” coming from? When I run the migration code, it creates an AspNetUsers table, in addition to the initial Users table. The only real thing I’m doing differently is I’ve got a different schema than the one you use in this article. But that can’t possibly be the reason for this to happen.

          Any thoughts? I’ve combed through my code, and nothing is jumping out at me. I’ve been able to run the code and the login and register pages will run without crashing, so there’s that. 🙂

          I am making progress. This is going to be really useful for my website. I really do appreciate the effort you put into this article.

          1. I’ve figured most of it out. Thank you Google. 🙂

            I took the services.AddDefaultIdentity… out of IdentityHostingStartup.

            I’ve kept the AspNetUsers table. It’s the only way I can get it to run completely.

            I added app.UseAuthentication() to Startup.Configure(…).

            Those three things have me to the point where I can log in and see what’s expected in the menu bar. I can click on my username and get to the configuration side menu. Now I need to make the changes you’ve outlined after that.

            I’ll keep you posted.

  21. Thanks Mukesh for such an enlightening tutorial, I followed the steps but I am getting an error on profile picture update, its saying

    The value ‘xxx.png’ is not valid for Profile Picture.

    Kindly assist.

  22. This was exactly what I needed! Thanks so much for helping this code noob make users and roles much easier! You saved me many many headaches. Your coffees should be in you inbox 😀

  23. Hi @Mukesh, thanks for this great tutorial!:) I have an issue thought during seeding…:/ It wont seed the roles! I am using VS 2019 and Asp.Net Core 5.0. The exception logger gets is the following :

    {“No service for type ‘Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]’ has been registered.”} System.Exception {System.InvalidOperationException}

    This is how my IdentityHostingStartup.cs looks like:

    [assembly: HostingStartup(typeof(YouPod.Areas.Identity.IdentityHostingStartup))]
    namespace YouPod.Areas.Identity
    {
    public class IdentityHostingStartup : IHostingStartup
    {
    public void Configure(IWebHostBuilder builder)
    {
    builder.ConfigureServices((context, services) =>
    {
    services.AddDbContext(options =>
    options.UseSqlServer(
    context.Configuration.GetConnectionString(“YouPodDbContextConnection”)));

    services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = false) //false for now and when I will configure SendGrid this should change to true
    .AddEntityFrameworkStores();
    });
    }
    }
    }

    and my program.cs is exactly like yours. Could I please ask for your input? Thanks!

      1. Hi Mukesh
        wonderful tutorial, i got through most of it , only one error i am not able to resolve at the moment.
        if you come across the solution do let me know..

        when iam trying to modify roles i get below exception…

        https://localhost:5001/UserRoles/Manage?userId=8ebb29e4-2d2e-46cd-a704-072cbc5a80b4

        An unhandled exception occurred while processing the request.
        InvalidOperationException: This MySqlConnection is already in use. See https://fl.vu/mysql-conn-reuse
        MySqlConnector.Core.ServerSession.StartQuerying(ICancellableCommand command) in ServerSession.cs, line 281

      2. hi Murkesh

        i got it fixed, its the
        foreach (var role in _roleManager.Roles) >>>> is changed to
        foreach (var role in _roleManager.Roles.ToList())

    1. I got this too – I had to go into Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml and change to . There was one more place I had to do that too in Views/Shared/_LoginPartial – same thing – to . Hope that helps!

  24. Hello Mukesh

    Thank you for your effort to write this amazing Tutorial.

    I have a Question:

    I can’t close any StatusMessage.
    I’ve downloaded your Project and it works but on my Project something is wrong.
    What i’ve tried is replacing content of this sites but with no success;

    _StatusMessage.cshtml -> Areas\Identity\Pages\Account\Manage\
    _StatusMessage.cshtml -> Areas\Identity\Pages\Account\
    Index.cshtml -> Areas\Identity\Pages\Account\Manage\
    Index.cshtml.cs -> Areas\Identity\Pages\Account\Manage\

    Also im a beginner. do you have any suggestions?

    I’ve updated my project to Bootstrap5 could this perhaps be the Problem?

    Thank you again for this great Tutorial it helped me a lot.

  25. Thanks you. Your code is amazing. I have a minor suggestion for your code.

    In Controller UserRole’s action Manage,
    foreach (var role in _roleManager.Roles) // change to foreach (var role in await _roleManager.Roles.ListAsnyc() )
    {
    . . .
    }
    Or it will raise an exception while running under Asp.Net Core 5. (ps: Does Asp.Net core 3 accept it ? )

  26. Hello Mister. excellent tutorial, thanks for sharing it. I got stock trying to Login with the default user credentials. When I put on Username box superadmin, it says that is not valid
    //Seed Default User
    var defaultUser = new ApplicationUser
    {
    UserName = “superadmin”,
    Email = “pruebasGuti_91@bussinessguti.com”,
    FirstName = “Herbert”,
    LastName = “Gutierrez”,
    EmailConfirmed = true,
    PhoneNumberConfirmed = false
    };
    if (userManager.Users.All(u => u.Id != defaultUser.Id))
    {
    var user = await userManager.FindByEmailAsync(defaultUser.Email);
    if (user == null)
    {

    await userManager.CreateAsync(defaultUser, “1234567.Guti”);
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Basic.ToString());
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Moderator.ToString());
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Admin.ToString());
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.SuperAdmin.ToString());
    }

    }

  27. Thanks for awesome tutorial. I got stocked trying to login with the default user’s username “superadmin”, and it says that is not valid. Am I doing something wrong ??? Or should I change it from my profile ??

    var defaultUser = new ApplicationUser
    {
    UserName = “superadmin”,
    Email = “pruebasGuti_91@bussinessguti.com”,
    FirstName = “Herbert”,
    LastName = “Gutierrez”,
    EmailConfirmed = true,
    PhoneNumberConfirmed = false
    };
    if (userManager.Users.All(u => u.Id != defaultUser.Id))
    {
    var user = await userManager.FindByEmailAsync(defaultUser.Email);
    if (user == null)
    {

    await userManager.CreateAsync(defaultUser, “1234567.Guti”);
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Basic.ToString());
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Moderator.ToString());
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Admin.ToString());
    await userManager.AddToRoleAsync(defaultUser, Enums.Roles.SuperAdmin.ToString());
    }

    }

    1. The username generating logic here in this code is from the email. i.e if email is pruebasGuti_91@bussinessguti.com, then username should be pruebasGuti_91 . But you assigned username different. I hope changing the username to that of email (before @) works.

  28. Mukesh, thank you so much for a detailed step-by-step explanation and clear guidance without any unnecessary BS. You saved me a loooot of time, thanks again and the best wishes!

  29. Hello, I have having an error whenever I am opening the page, although I can close this error and still register and data will still be stored. But every time I navigate through pages this error is always showing.

    Unhandled Rejectiaon (Error): Could not load settings for ‘Application.Web’ AuthorizeService.ensureUserManagerInitialized

    Anyone can help me out. Kindly acknowledge my question, please. Thank you.

  30. Hello, it’s odd that the code works to others, but in my case it does not.

    [HttpPost]
    public async Task AddRole(string roleName)
    {
    if (roleName != null){
    await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
    }
    return RedirectToAction(“Index”);
    }

    Hello, on my end, this does not work. Can you help me please? thank you

    1. I got the same problem as you.
      Please check the Index.cshtml view and if you adding the line:
      @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

      at the top of the view it will work.
      And I am wondering why I need to add this line at each view when I have added it to _viewimports.cshtml.

      And I have asked Muskesh about this.

  31. hi i follow the step by step instructions , user registration is ok but when i do the login it says
    Invalid login attempt.

    i am using .Net core 3.1

  32. thank you very much for the great work , in fact i know many things here long time i tried to obtain but now it is ok ,,, thanks again sir.

  33. Adding the override function to the ApplicationDbContext.cs file gives me errors.

    “A namespace cannot directly contain members such as fields or members”

    “no suitable method found to override”

  34. var roleManager = services.GetRequiredService<RoleManager>();

    Error
    No service for type ‘Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]’ has been registered

  35. thanks you.

    But, It have a issue.
    ‘OnModelCreating method’ in ApplicationDbContext.cs

    if you want to change the table name from database. you must try change.

    ✅From
    builder.Entity(entity =>
    {
    entity.ToTable(name: “User”);
    });

    ✅to
    builder.Entity(entity =>
    {
    entity.ToTable(name: “User”);
    });

    1. ✅From
      “`c#
      builder.Entity(entity =>
      {
      entity.ToTable(name: “User”);
      });
      “`
      ✅to
      “`c#
      builder.Entity(entity =>
      {
      entity.ToTable(name: “User”);
      });
      “`

      1. ✅From

        builder.Entity(entity =>
        {
        entity.ToTable(name: “User”);
        });

        ✅to

        builder.Entity(entity =>
        {
        entity.ToTable(name: “User”);
        });

  36. Hi Mukesh,
    One of the best blog I’ll say..it helps me lot to understand the new stuff and implement it in my upcoming solutions.
    Can you please suggest some better way to prevent multiple & concurrent login in .Net Core?
    Thanks.

  37. About section “40+ Identity pages” and “But even after that you would have to manually go to each page to add the namespace reference”. When upgrade to .NET 6, you can solve this issue by using the new global usings feature of C# 10. For example: just add GlobalUsings.cs with this line: global using UserManagement.MVC.Models;

    Thanks for your awesome blog!

  38. Hi Mukesh,

    Thanks for the excellent tutorial for using Identity and Roles.

    I have a small issue. When trying to Manage User Roles by clicking on Manage button https:///UserRoles/Manage, I get InvalidOperationException: The view ‘NotFound’ was not found. The following locations were searched: /Views/UserRoles/NotFound.cshtml /Views/Shared/NotFound.cshtml /Pages/Shared/NotFound.cshtml

    Can you point me towards resolution?

    Thanks

  39. Hi, Mukesh.

    Very good tutorial.

    I’m arriving to Blazor. I’m creating an app with the server option.
    Instead of having Views and Controllers, I would like to have the same funcionality with razor components.

    Can you guide me? Is it something feasible?

    Regards,
    Fausto

  40. Hi,
    Thank for the detailed tutorial about user management in ASP.NET Core.
    But when I try to add the Firstname and Lastname to the database, the code always create the User table but also the old table AspNetUsers. I tried this in VS2019 and VS2022 Preview, both Visual Studios have their latest updates installed.
    The only solution have found is manually change the code in de migration file.
    Have you an idea how to fix this or what the problem would be?

    Thanks in advanced.

    1. I guess you are not extending the IdentityUser class. Did you inherit you User class from the IdentityUser class? That would be the only reason 2 tables are getting created for you.
      Thanks

      1. Thanks for the replay.

        Yes I did. I put the code of my ApplicationUser class below.
        public class ApplicationUser : IdentityUser
        {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string NickName { get; set; }
        } // end
        Best regards.
        Danny

  41. Hi, i have put credentials in fields and clicked register button, and i works, it even redirects to home page, but when i look in database in table Identity.User, there are no data in there.

  42. In the startup.cs file
    services.AddDefaultIdentity(options =>

    options.SignIn.RequireConfirmedAccount = true;
    )
    here if i change this false then i can register otherwise it is showing error.

    After register I can’t login . Although all information saved in database.
    What’s the issue?

  43. Hi
    public async Task Manage(string userId)
    {
    ViewBag.userId = userId;
    var user = await _userManager.FindByIdAsync(userId);
    if (user == null)
    {
    ViewBag.ErrorMessage = $”L’utilisateur avec l’identifiant = {userId} est introuvable”;
    return View(“NotFound”);
    }
    ViewBag.UserName = user.UserName;
    var model = new List();
    foreach (var role in _roleManager.Roles.ToList())
    {
    var userRolesViewModel = new ManageUserRolesViewModel
    {
    RoleId = role.Id,
    RoleName = role.Name
    };

    Error in
    await _userManager.IsInRoleAsync(user, role.Name)
    An unhandled exception occurred while processing the request.
    NotSupportedException: Store does not implement IUserRoleStore.

    Can you help me thanks