asp.net-core-mvc - 根据用户角色加载不同的 View asp.net core mvc

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

我是 asp.netcore MVC 新手

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

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

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

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

谢谢

最佳答案

这里有一些有关使用 Asp.net Core Identity 管理用户和角色以及实现基于角色的身份验证的相关文章。你可以引用一下:

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身份配置应用程序并添加Role授权后。

在 View 页面中,您可以使用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>
    }

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

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

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

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

enter image description here

关于asp.net-core-mvc - 根据用户角色加载不同的 View asp.net core mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66873146/

相关文章:

c# - ASP.NET Core Identity - 创建用户 "manually"并提供密码哈希 - 如何正确生成哈希?

asp.net-mvc - 由于vs2015中invokepowershell失败,无法发布mvc6应用程序

c# - ASP.NET Core MVC 应用程序中的 Microsoft LocalReport (rdl)

postgresql - 无法使用 ASP.NET Core 和身份添加声明

c# - IdentityUser 的 IUserValidator

c# - 身份不工作,无法访问身份数据

asp.net-core - 使用 .Net Core 安装 DotLiquid 时出现 NU1108 错误

asp.net-core - ASP.NET Core 清除 session 问题

c# - 是否可以在 ASP.NET Core MVC 应用程序中运行 Blazor 客户端页面?

c# - 相当于 ASP.NET Core 2.0 中的 GetExternalAuthenticationTypes()?