Search code examples
asp.net-core-mvcasp.net-core-identity

Load different views dependant on user role asp.net core mvc


I am new to asp.netcore MVC

I am wanting to load different views dependant on the user's role e.g.

if (role == "Admin")
   return view("admin")
else if (role == "Other")
   return  view("index")

I know you can use the [authorize(Role = ... and the asp.net core identity api.

I was wondering if anyone can point me to a good tutorial that dealt with this?

Thanks


Solution

  • Here are some related articles about using Asp.net Core Identity to manage users and roles, and implement Role-Based Authentication. You could refer to them:

    Introduction to Identity on ASP.NET Core

    How to work with Roles in ASP.NET Core Identity

    Role-based authorization in ASP.NET Core

    Adding Role Authorization to a ASP.NET MVC Core Application

    Then, after configuring the application using Asp.net Core identity and add the Role authorization.

    In the view page, you could use the Context.User.IsInRole method to check whether current user is in the specified role. Then, load the related content. Code like this:

        @if (Context.User.IsInRole("Admin"))
        { 
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="" asp-controller="Role" asp-action="Index">Role</a>
            </li>
        }
    

    In the controller, to return different view based on the role. We could use HttpContext.User.IsInRole method to check whether user in the specified role. For example:

        public IActionResult Index()
        { 
            if (HttpContext.User.IsInRole("Admin"))
            {
                return View("Privacy");
            } 
            return View();
        }
    

    Besides, we could also use the UserManager.IsInRoleAsync() Method to check it.

    By using the above sample code, the result like this:

    enter image description here