【问题标题】:Load different views dependant on user role asp.net core mvc根据用户角色加载不同的视图 asp.net core mvc
【发布时间】:2021-03-31 09:43:38
【问题描述】:

我是 asp.netcore MVC 的新手

我想根据用户的角色加载不同的视图,例如

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

我知道你可以使用 [authorize(Role = ... 和 asp.net core identity api。

我想知道是否有人可以指出一个处理这个问题的好教程?

谢谢

【问题讨论】:

    标签: asp.net-core-mvc asp.net-core-identity


    【解决方案1】:

    这里有一些关于使用 Asp.net Core Identity 管理用户和角色,以及实现 Role-Based Authentication 的相关文章。你可以参考他们:

    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

    然后,在使用 Asp.net Core 身份配置应用程序并添加角色授权后。

    在查看页面中,您可以使用Context.User.IsInRole 方法检查当前用户是否处于指定角色。然后,加载相关内容。像这样的代码:

        @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>
        }
    

    在控制器中,根据角色返回不同的视图。我们可以使用HttpContext.User.IsInRole 方法来检查用户是否在指定的角色中。例如:

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

    此外,我们还可以使用UserManager.IsInRoleAsync() Method 进行检查。

    使用上面的示例代码,结果如下:

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      相关资源
      最近更新 更多