Monday 21 September 2020

MVC Core Identity

In this demo will demonstrate,

1.       How to customize Identity?
2.       How to create Roles?
3.       How to assign Role to Users?
4.       How to set user rights to access particular menu or action?

Using Entity Framework

Key Features Point: -

1. Controller Admin, User
2. Models
1.       ApplicationDbContext.cs
2.       RoleModel.cs
3.       UserModel.cs
4.       UserRoleModel.cs
3. Views
Admin
1.       Create.cshtml
2.       Delete.cshtml
3.       DeleteUser.cshtml
4.       Details.cshtml
5.       Edit.cshtml
6.       EditUser.cshtml
7.       ListRoles.cshtml
8.       ListUsers.cshtml
9.       ManageUserInRole.cshtml
10.   UserDetails.cshtml
User
1.       Index.cshtml
Shared

1.       NotFound.cshtml 

To Do: -

1. Install following packages using Manage NuGet Packages… manager

1.       Microsoft.EntityFrameworkCore --To use EF 
2.       Microsoft.EntityFrameworkCore.Design --To Enable Scaffolding 
3.       Microsoft.EntityFrameworkCore.SqlServer --To Enable Sql Server
4.       Microsoft.EntityFrameworkCore.Tools --To Enable Migration command
5.       Microsoft.AspNetCore.Identity.EntityFrameworkCore To Enable Identity

2. Configure connection string in appsettings.json
3. Register database in Startup.cs
4. Register identity in Startup.cs
5. Register AddRazorPages in Startup.cs
6. Register MapRazorPages() in Startup.cs
7. Register UseAuthentication() in Startup.cs

Migration Command: -

1. Add-Migration InitDbCreate
2. Update-Database
3. Remove-migration

Let’s Start

Step 1: - Launch Visual Studio 2019 => Click on Create a new project from the list



Step 2: - Choose ASP.NET Core Web Application from the list



Step 3: - Type Project name MVCCoreIdentity => Click on Create



Step 4: - Choose Web Application (Model-View-Controller) from the list




Step 5: - Install following packages using Manage NuGet Packages… manager => Right click on Dependencies => Click on Manage NuGet Packages… => Search Package & Install

1.       Microsoft.EntityFrameworkCore --To Enable EF

2.       Microsoft.EntityFrameworkCore.Design --To Enable Scaffolding

3.       Microsoft.EntityFrameworkCore.SqlServer --To Enable Sql Server

4.       Microsoft.EntityFrameworkCore.Tools --To Enable Migration command

5.       Microsoft.AspNetCore.Identity.EntityFrameworkCore To Enable Identity

 





Step 6: - Open appsettings.json file from Solution Explorer => => Copy Past following code in appsettings.json file

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
  "ApplicationContext": "Server=(localdb)\\mssqllocaldb;Database=MVCCoreIdentity;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

}

 

Step 7: - Right click on Models folder => Add => Click New Items... => Expand Visual C# from left pane => Select Class from middle pane => Type UserModel.cs in the Name box => Click on Add => Copy Past following code in UserModel.cs file

 

using Microsoft.AspNetCore.Identity;
 
namespace MVCCoreIdentity.Models
{
    public class UserModel : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MobileNo { get; set; }
    }

}

 

Step 8: - Right click on Models folder => Add => Click New Items... => Expand Visual C# from left pane => Select Class from middle pane => Type ApplicationDbContext.cs in the Name box => Click on Add => Copy Past following code in ApplicationDbContext.cs file

 

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using MVCCoreIdentity.Models;
 
namespace MVCCoreIdentity.Models
{
    public class ApplicationDbContext : IdentityDbContext<UserModel>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }

}

Step 9: - Open Startup.cs file from Solution Explorer => Copy Past following code in Startup.cs file

using MVCCoreIdentity.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
 
namespace MVCCoreIdentity
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        public IConfiguration Configuration { get; }
 
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
 
     services.AddRazorPages();
 
            services.AddDbContext<ApplicationDbContext>(
                options => options.UseSqlServer(Configuration
                .GetConnectionString("ApplicationContext")));
 
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
 
            app.UseRouting();
 
     app.UseAuthentication();//Enable Authentication;
 
            app.UseAuthorization();
 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }

}

 

Build Project

Step 10: - Open Package Manager Console => Type Command Add-Migration InitDbCreate => Press Enter



Step 11: - Open SQL Server Object Explorer => Database created successfully




Step 12: - Right click on Project Root folder => Add => New Scaffolded Item... => Select Identity from left pane=> Select Identity from middle pane => Click on Add => Tick Override all files => Select Data context class: ApplicationDbContext(MVCCoreIdentity.Models) => Click on Add






Step 13: - Open Solution Explorer => Expand Area folder => Expand Identity folder => Expand Pages folder => Expand Account folder => Expand Register.cshtml file => Select Register.cshtml.cs => Copy Past following code in Register.cshtml.cs file

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using MVCCoreIdentity.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
 
namespace MVCCoreIdentity.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class RegisterModel : PageModel
    {
        private readonly SignInManager<UserModel> _signInManager;
        private readonly UserManager<UserModel> _userManager;
        private readonly ILogger<RegisterModel> _logger;
        private readonly IEmailSender _emailSender;
 
        public RegisterModel(
            UserManager<UserModel> userManager,
            SignInManager<UserModel> signInManager,
            ILogger<RegisterModel> logger,
            IEmailSender emailSender)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
        }
 
        [BindProperty]
        public InputModel Input { get; set; }
 
        public string ReturnUrl { get; set; }
 
        public IList<AuthenticationScheme> ExternalLogins { get; set; }
 
        public class InputModel
        {
            [Required]
            [EmailAddress]
            [Display(Name = "Email")]
            public string Email { get; set; }
 
            [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }
 
            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }
 
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "First Name")]
            public string FirstName { get; set; }
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Last Name")]
            public string LastName { get; set; }
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Mobile No")]
            public string MobileNo { get; set; }
        }
 
        public async Task OnGetAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        }
 
        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new UserModel
                {
                    FirstName = Input.FirstName,
                    LastName = Input.LastName,
                    MobileNo = Input.MobileNo,
                    UserName = Input.Email,
                    Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
 
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);
 
                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
 
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return LocalRedirect(returnUrl);
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
 
            // If we got this far, something failed, redisplay form
            return Page();
        }
    }

}

Step 14: - Open Solution Explorer => Expand Area folder => Expand Identity folder => Expand Pages folder => Expand Account folder => Select Register.cshtml  => Copy Past following code in Register.cshtml file

@page
@model RegisterModel
@{
    ViewData["Title"] = "Register";
}
 
<h1>@ViewData["Title"]</h1>
 
<div class="row">
    <div class="col-md-4">
        <form asp-route-returnUrl="@Model.ReturnUrl" method="post">
            <h4>Create a new account.</h4>
            <hr />
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Input.FirstName"></label>
                <input asp-for="Input.FirstName" class="form-control" />
                <span asp-validation-for="Input.FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.LastName"></label>
                <input asp-for="Input.LastName" class="form-control" />
                <span asp-validation-for="Input.LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.MobileNo"></label>
                <input asp-for="Input.MobileNo" class="form-control" />
                <span asp-validation-for="Input.MobileNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.Email"></label>
                <input asp-for="Input.Email" class="form-control" />
                <span asp-validation-for="Input.Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.Password"></label>
                <input asp-for="Input.Password" class="form-control" />
                <span asp-validation-for="Input.Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.ConfirmPassword"></label>
                <input asp-for="Input.ConfirmPassword" class="form-control" />
                <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-primary">Register</button>
        </form>
    </div>
    <div class="col-md-6 col-md-offset-2">
        <section>
            <h4>Use another service to register.</h4>
            <hr />
            @{
                if ((Model.ExternalLogins?.Count ?? 0) == 0)
                {
                    <div>
                        <p>
                            There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
                            for details on setting up this ASP.NET application to support logging in via external services.
                        </p>
                    </div>
                }
                else
                {
                    <form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
                        <div>
                            <p>
                                @foreach (var provider in Model.ExternalLogins)
                                {
                                    <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                                }
                            </p>
                        </div>
                    </form>
                }
            }
        </section>
    </div>
</div>
 
@section Scripts {
    <partial name="_ValidationScriptsPartial" />

}

 

Step 15: - Right click on Models folder => Add => Click New Items... => Expand Visual C# from left pane => Select Class from middle pane => Type RoleModel.cs in the Name box => Click on Add => Copy Past following code in RoleModel.cs file

 

using System.ComponentModel.DataAnnotations;
 
namespace MVCCoreIdentity.Models
{
    public class RoleModel
    {
        public string Id { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Role Name")]
        public string Name { get; set; }
    }

}

 

Step 16: - Right click on Models folder => Add => Click New Items... => Expand Visual C# from left pane => Select Class from middle pane => Type UserRoleModel.cs in the Name box => Click on Add => Copy Past following code in UserRoleModel.cs file

 

namespace MVCCoreIdentity.Models
{
    public class UserRoleModel
    {
        public int Id { get; set; }
        public string UserId { get; set; }
        public string UserName { get; set; }
        public bool IsChecked { get; set; } = false;
    }

}

 

Build Application

 

Step 17: - Right click on Controller folder => Add => Controller... => Select MVC Controller – Empty => Click on Add => Type name AdminController.cs => Click on Add => Copy Past following code in AdminController.cs file

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using MVCCoreIdentity.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MVCCoreIdentity.Controllers
{

    //[Authorize(Roles = "Administrator")]

    public class AdminController : Controller
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<UserModel> _userManager;
 
        public AdminController(
            RoleManager<IdentityRole> roleManager,
            UserManager<UserModel> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }
 
        public ActionResult ListRoles()
        {
            var roles = _roleManager.Roles;
 
            List<RoleModel> roleModel = new List<RoleModel>();
 
            foreach (var item in roles)
            {
                roleModel.Add(new RoleModel() { Id = item.Id, Name = item.Name });
            }
 
            return View(roleModel);
        }
 
        public async Task<ActionResult> Details(string id)
        {
            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {
                ViewBag.Message = $"Role with Id = {id} cannot be found!";
                return View("NotFound");
            }
            RoleModel roleModel = new RoleModel() { Id = role.Id, Name = role.Name };
            return View(roleModel);
        }
 
        public ActionResult Create()
        {
            return View();
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(RoleModel roleModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var roleExists = await _roleManager.RoleExistsAsync(roleModel.Name);
                    if (!roleExists)
                    {
                        await _roleManager.CreateAsync(new IdentityRole(roleModel.Name));
                        return RedirectToAction(nameof(ListRoles));
                    }
                    else
                        ModelState.AddModelError("", "Role already exists.");
                }
                return View();
            }
            catch
            {
                return View();
            }
        }
 
        public async Task<ActionResult> Edit(string id)
        {
            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {
                ViewBag.Message = $"Role with Id = {id} cannot be found!";
                return View("NotFound");
            }
            RoleModel roleModel = new RoleModel() { Id = role.Id, Name = role.Name };
            return View(roleModel);
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(string id, RoleModel roleModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var role = await _roleManager.FindByIdAsync(id);
                    if (role == null)
                    {
                        ViewBag.Message = $"Role with Id = {id} cannot be found!";
                        return View("NotFound");
                    }
 
                    role.Name = roleModel.Name;
 
                    await _roleManager.UpdateAsync(role);
                    return RedirectToAction(nameof(ListRoles));
                }
                return View();
            }
            catch
            {
                return View();
            }
        }
 
        public async Task<ActionResult> Delete(string id)
        {
            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {
                ViewBag.Message = $"Role with Id = {id} cannot be found!";
                return View("NotFound");
            }
            RoleModel roleModel = new RoleModel() { Id = role.Id, Name = role.Name };
            return View(roleModel);
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Delete(string id, RoleModel roleModel)
        {
            try
            {
                var role = await _roleManager.FindByIdAsync(id);
                if (role == null)
                {
                    ViewBag.Message = $"Role with Id = {id} cannot be found!";
                    return View("NotFound");
                }
                await _roleManager.DeleteAsync(role);
                return RedirectToAction(nameof(ListRoles));
            }
            catch
            {
                return View();
            }
        }
 
        public async Task<ActionResult> ManageUserInRole(string id)
        {
            ViewBag.RoleId = id;
            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {
                ViewBag.Message = $"Role with Id = {id} cannot be found!";
                return View("NotFound");
            }
            ViewBag.RoleName = role.Name;
            List<UserRoleModel> userRoleModels = new List<UserRoleModel>();
            foreach (var item in _userManager.Users)
            {
                UserRoleModel userRoleModel = new UserRoleModel()
                {
                    UserId = item.Id,
                    UserName = item.UserName,
                    IsChecked = await _userManager.IsInRoleAsync(item, role.Name)
                };
                userRoleModels.Add(userRoleModel);
            }
            return View(userRoleModels);
        }
 
        [HttpPost]
        public async Task<ActionResult> ManageUserInRole(string id, List<UserRoleModel> userRoleModels)
        {
            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {
                ViewBag.Message = $"Role with Id = {id} cannot be found!";
                return View("NotFound");
            }
            for (int i = 0; i < userRoleModels.Count; i++)
            {
                var user = await _userManager.FindByIdAsync(userRoleModels[i].UserId);
 
                if (userRoleModels[i].IsChecked && !await _userManager.IsInRoleAsync(user, role.Name))
                {
                    await _userManager.AddToRoleAsync(user, role.Name);
                }
                else if (!userRoleModels[i].IsChecked && await _userManager.IsInRoleAsync(user, role.Name))
                {
                    await _userManager.RemoveFromRoleAsync(user, role.Name);
                }
            }
            return RedirectToAction("ManageUserInRole", new { id = id });
        }
 
        [HttpGet]
        public ActionResult ListUsers()
        {
            var users = _userManager.Users;
            return View(users);
        }
 
        public async Task<ActionResult> UserDetails(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.Message = $"User with Id = {id} cannot be found!";
                return View("NotFound");
            }
            UserModel userModel = new UserModel()
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.LastName,
                MobileNo = user.MobileNo,
                Email = user.Email
            };
            return View(userModel);
        }
 
        public async Task<ActionResult> EditUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.Message = $"User with Id = {id} cannot be found!";
                return View("NotFound");
            }
            UserModel userModel = new UserModel()
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.LastName,
                MobileNo = user.MobileNo,
                Email = user.Email
            };
            return View(userModel);
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> EditUser(string id, UserModel userModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var user = await _userManager.FindByIdAsync(id);
                    if (user == null)
                    {
                        ViewBag.Message = $"User with Id = {id} cannot be found!";
                        return View("NotFound");
                    }
 
                    user.FirstName = userModel.FirstName;
                    user.LastName = userModel.LastName;
                    user.MobileNo = userModel.MobileNo;
                    user.Email = userModel.Email;
 
                    await _userManager.UpdateAsync(user);
                    return RedirectToAction(nameof(ListUsers));
                }
                return View();
            }
            catch
            {
                return View();
            }
        }
 
        public async Task<ActionResult> DeleteUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.Message = $"User with Id = {id} cannot be found!";
                return View("NotFound");
            }
            return View(user);
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteUser(string id, UserModel userModel)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id);
                if (user == null)
                {
                    ViewBag.Message = $"User with Id = {id} cannot be found!";
                    return View("NotFound");
                }
                await _userManager.DeleteAsync(user);
                return RedirectToAction(nameof(ListUsers));
            }
            catch
            {
                return View();
            }
        }
    }

}

Step 18: - Right click on Views folder => Add => New folder => Type name Admin folder

Step 19: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name ListRoles.cshtml => Copy Past following code in ListRoles.cshtml file

@model IEnumerable<MVCCoreIdentity.Models.RoleModel>
 
@{
    ViewData["Title"] = "Index";
}
 
<h1>List of Roles</h1>
 
<hr />
<p>
    <a asp-action="Create">Create New Role</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>|
                    <a asp-action="ManageUserInRole" asp-route-id="@item.Id">Add or Remove User</a>
                </td>
            </tr>
        }
    </tbody>

</table>

Step 20: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name Details.cshtml => Copy Past following code in Details.cshtml file

@model MVCCoreIdentity.Models.RoleModel
 
@{
    ViewData["Title"] = "Details";
}
 
<h1>Role Details</h1>
 
<hr />
<div>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="ListRoles">Back to List</a>

</div>

Step 21: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name Create.cshtml => Copy Past following code in Create.cshtml file

@model MVCCoreIdentity.Models.RoleModel
 
@{
    ViewData["Title"] = "Create";
}
 
<h1>Create Role</h1>
 
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
 
<div>
    <a asp-action="ListRoles">Back to List</a>

</div>

 

Step 22: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name Edit.cshtml => Copy Past following code in Edit.cshtml file

@model MVCCoreIdentity.Models.RoleModel
 
@{
    ViewData["Title"] = "Edit";
}
 
<h1>Edit Role</h1>
 
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
 
<div>
    <a asp-action="ListRoles">Back to List</a>

</div>

 

Step 23: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name Delete.cshtml => Copy Past following code in Delete.cshtml file

@model MVCCoreIdentity.Models.RoleModel
 
@{
    ViewData["Title"] = "Delete";
}
 
<h1>Delete Role</h1>
 
<hr />
<h3>Are you sure you want to delete this?</h3>
<div>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
    </dl>
 
    <form asp-action="Delete">
        <input type="hidden" asp-for="Id" />
        <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?');" /> |
        <a asp-action="ListRoles">Back to List</a>
    </form>

</div>

 

Step 24: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name ManageUserInRole.cshtml => Copy Past following code in ManageUserInRole.cshtml file

@model List<MVCCoreIdentity.Models.UserRoleModel>
 
@{
    ViewData["Title"] = "ManageUserInRole";
}
 
<h1>Add or Remove users from <u>@ViewBag.RoleName</u> role</h1>
 
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="ManageUserInRole">
            @for (int i = 0; i < Model.Count(); i++)
            {
                <div class="form-check m-1">
                    <input type="hidden" asp-for="@Model[i].UserId" />
                    <input type="hidden" asp-for="@Model[i].UserName" />
                    <input asp-for="@Model[i].IsChecked" class="form-check-input" />
                    <label class="form-check-label" asp-for="@Model[i].IsChecked">
                        @Model[i].UserName
                    </label>
                </div>
            }
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
 
<div>
    <a asp-action="ListRoles">Back to List</a>

</div>

 

Step 25: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name ListUsers.cshtml => Copy Past following code in ListUsers.cshtml file

@model IEnumerable<MVCCoreIdentity.Models.UserModel>
 
@{
    ViewData["Title"] = "Index";
}
 
<h1>List of Users</h1>
 
<hr />
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MobileNo)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.FirstName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.LastName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.MobileNo)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Email)
                </td>
                <td>
                    <a asp-action="EditUser" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="UserDetails" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="DeleteUser" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>

</table>

Step 26: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name UserDetails.cshtml => Copy Past following code in UserDetails.cshtml file

@model MVCCoreIdentity.Models.UserModel
 
@{
    ViewData["Title"] = "UserDetails";
}
 
<h1>User Details</h1>
 
<hr />
<div>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.FirstName)
        </dd>
    </dl>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.LastName)
        </dd>
    </dl>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.MobileNo)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.MobileNo)
        </dd>
    </dl>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Email)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Email)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="EditUser" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="ListUsers">Back to List</a>

</div>

 

Step 27: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name EditUser.cshtml => Copy Past following code in EditUser.cshtml file

@model MVCCoreIdentity.Models.UserModel
 
@{
    ViewData["Title"] = "EditUser";
}
 
<h1>Edit User</h1>
 
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="EditUser">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="FirstName" class="control-label"></label>
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LastName" class="control-label"></label>
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="MobileNo" class="control-label"></label>
                <input asp-for="MobileNo" class="form-control" />
                <span asp-validation-for="MobileNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
 
<div>
    <a asp-action="ListUsers">Back to List</a>

</div>

 

Step 28: - Right click on Admin folder => Add => View => Select Razor View – Empty => Type name DeleteUser.cshtml => Copy Past following code in DeleteUser.cshtml file

@model MVCCoreIdentity.Models.UserModel
 
@{
    ViewData["Title"] = "DeleteUser";
}
 
<h1>Delete User</h1>
 
<hr />
<h3>Are you sure you want to delete this?</h3>
<div>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.FirstName)
        </dd>
    </dl>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.LastName)
        </dd>
    </dl>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.MobileNo)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.MobileNo)
        </dd>
    </dl>
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Email)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Email)
        </dd>
    </dl>
 
    <form asp-action="DeleteUser">
        <input type="hidden" asp-for="Id" />
        <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?');" /> |
        <a asp-action="ListUsers">Back to List</a>
    </form>

</div>

 

Step 29: - Right click on Controller folder => Add => Controller... => Select MVC Controller – Empty => Click Add => Type name UserController.cs => Click on Add => Copy Past following code in UserController.cs file

using Microsoft.AspNetCore.Mvc;
 
namespace MVCCoreIdentity.Controllers
{
    //[Authorize(Roles = "User")]
    public class UserController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

}

 

Step 30: - Right click on Views folder => Add => New folder => Type name User folder

Step 31: - Right click on User folder => Add => View => Select Razor View – Empty => Type name Index.cshtml => Copy Past following code in Index.cshtml file

 

@{
    ViewData["Title"] = "Index";
}
 

<h1>User Page</h1>

 

Step 32: - Right click on Shared folder => Add => View => Select Razor View – Empty => Type name NotFound.cshtml => Copy Past following code in NotFound.cshtml file

<h1>@ViewBag.Message</h1>

  

Step 33: - Expand Shared folder => Open _Layout.cshtml => Copy Past following code in _Layout.cshtml file

@using Microsoft.AspNetCore.Identity
@using MVCCoreIdentity.Models
 
@inject SignInManager<UserModel> SignInManager
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MVCCoreIdentity </title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MVCCoreIdentity</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                    <partial name="_LoginPartial" />
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>
 
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="User" asp-action="Index">User</a>
                        </li>
 
                        @if (SignInManager.IsSignedIn(User) && User.IsInRole("Administrator"))
                        {
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Admin" asp-action="ListRoles">Manage Roles</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-controller="Admin" asp-action="ListUsers">Manage Users</a>
                            </li>
                        }
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>
 
    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2020 - MVCCoreIdentity - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>

</html>


 

Step 34: - Open Startup.cs file from Solution Explorer => Add following line in ConfigureServices method

using Microsoft.AspNetCore.Identity;

services.AddDefaultIdentity<UserModel>()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();


 

 

Build & Run Project


Step 35: - Follow below steps 

1st create 2 User – Ram, Gopal

2nd create 2 Role – Administrator, User

3rd Assign Administrator Role to Ram

4th Assign User Role to Gopal

5th Stop Application

6th Go to AdminController => Uncomment [Authorize(Roles = "Administrator")] attribute

7th Go to UserController  => Uncomment [Authorize(Roles = "User")] attribute

8th Run Project


Output



 

 

 

 

 

 

 

 

 

 


1 comment:

  1. Very well explained! Keep posting the great content. Well, we have posted some interesting blog about Top 4 Latest ASP DOT NET Core Features - let's have a look

    ReplyDelete