Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Few user management operations using Identity Framework in ASP.NET MVC

    • 0
    • 3
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 368
    Comment on it

    In this blog you will see some code samples that you might find useful while accomplishing simple user management tasks like creating a user, assigning a role and so on. Following code samples assume that you have created an ASP.NET MVC application which by default includes references and code files supporting the Identity Framework.
     

    Following tasks have been covered in this blog and are accompanied with proper comments.

    1. Adding a user and assign a role.
    2. Checking if user belongs to a given role.
    3. Deleting a user
       

    Default references for Identity Framework added in the project
     


     

    Note: These samples were created using Visual Studio 2015 professional.
     

    1- Adding a user and assign a role ("Nurse" in this example)
     

    In the following code snippet, RegisterViewModel class is strongly bind to the view AddUser which will be submitting the POST request to AddUser action in following snippet. This view provide following details of a user and add that user in the database using Identity Framework.

    1. Username
    2. Email
    3. Password

     

    First let's see the model class that will be used while adding a user. This class RegisterViewModel (can have other name as per your requirement) is supposed to be created inside Models folder.
     

    RegisterViewModel.cs

     

    //namespaces required
    using System.ComponentModel.DataAnnotations;
    
    public class RegisterViewModel
    {
        [Required]
        public string Username { get; set; }
    
        [Required]
        [EmailAddress]
        public string Email { get; set; }
    
        [Required]
        [MinLength(8, ErrorMessage = "Password must be atleast 8 characters long.")]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [DataType(DataType.Password)]
        [Display(Name = "Retype Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

     

    Controller file will have namespaces and code as follows. Here "YourSolutionName" will be your project name.

     

    //namespaces required
    using YourSolutionName.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using System;
    using System.Web;
    using System.Web.Mvc;
    
    
    // Following code to be placed inside your controller class
    
    private ApplicationUserManager _userManager;
    
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
    
    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult AddUser(RegisterViewModel model)
    {
       if (ModelState.IsValid)
       {
          try
          {
             using (var context = new ApplicationDbContext())
             {
                var applicationUser = new ApplicationUser { UserName = model.Username, Email = model.Email };
                
                var createResult = UserManager.Create(applicationUser, model.Password);
    
                if (!createResult.Succeeded)
                    // If user is not successfully created then add respective error to ModelState to show them in view
                    AddErrors(createResult);
                else
                {
                    var addRoleResult = UserManager.AddToRole(applicationUser.Id, "Nurse");
    
                    if (!addRoleResult.Succeeded)
                        // If user is successfully added but problem occurs while adding a role to it, then add error details to ModelState
                        AddErrors(createResult);
                    else
                    {
                       // Return message that user has been successfully created and assigned a role
                    }
                }
             }
          }
          catch (Exception ex)
          {
             // Log exception and return message showing that some problem has occurred
          }
       }
     
       return View();
    }
    
    
    // Method to iterate through error list and add them to ModelState
    private void AddErrors(IdentityResult result)
    {
         foreach (var error in result.Errors)
         {
             ModelState.AddModelError("", error);
         }
    }

     

    2- Checking if user belongs to a given role ("Nurse" role in this example)
     

    In the following code snippet, userName provided from the view is further passed to a function IsUserWithNurseRole(), which returns true if user has been assigned a Nurse role else it will return false. Here "YourSolutionName" will be your project name.

     

    //namespaces required
    using YourSolutionName.Models;
    using Microsoft.AspNet.Identity;
    using System;
    using System.Linq;
    using System.Web.Mvc;
    
    
    // Following code to be placed inside your controller class
    
    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult CheckRole(string userName)
    {
        try
        {
            bool isNurse = IsUserWithNurseRole(userName);
            if (isNurse)
            {
                // Perform operations for "Nurse" user
            }
            else
            {
                // Perform operations for user other than "Nurse"
            }
        }
        catch (Exception ex)
        {
            // Log exception and return message showing that some problem has occurred
        }
        return View();
    }
    
    private bool IsUserWithNurseRole(string userName)
    {
        using (var context = new ApplicationDbContext())
        {
            using (var userManager = new UserManager<ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(context)))
            {
                var user = userManager.FindByName(userName);
    
                // Get details about the "Nurse" role
                var role = (from r in context.Roles where r.Name.Contains("Nurse") select r).FirstOrDefault();
    
                // Check if user is a valid user and user's role id match with the role id of Nurse
                if (user != null && user.Roles.Any(x => x.RoleId == role.Id && x.UserId == user.Id))
                {
                    return true;
                }
            }
        }
        return false;
    }

     

    3- Deleting a user


    In the following code snippet, email received from the view is used to retrieve the object of type ApplicationUser after matching it with the email addresses of all users in the database.

    Once we have a valid user corresponding to the provided email, we can pass that user object to Delete method available in static class UserManagerExtensions from Microsoft.AspNet.Identity namespace. Here "YourSolutionName" will be your project name.
     

    //namespaces required
    using YourSolutionName.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Linq;
    using System.Web.Mvc;
    
    
    // Following code to be placed inside your controller class
    
    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteUser(string email)
    {
        using (var context = new ApplicationDbContext())
        {
            try
            {
                // Get "ApplicationUser" object representing a user who has a matching email address
                var user = context.Users.Where(x => x.Email == email).FirstOrDefault();
    
                // if user exists
                if (user != null)
                {
                    using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)))
                    {
                        userManager.Delete(user);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "User not found corresponding to provided email address.");
                }
            }
            catch (Exception ex)
            {
                // Log exception and show appropriate message
            }
        }
    
        return View();
    }

     

     

    Few user management operations using Identity Framework in ASP.NET MVC

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: