7

我已经使用 razor 引擎创建了 asp.net mvc4 应用程序,我是这项技术的新手,并试图找出一种在管理员登录后向管理员显示注册用户列表的方法。会员资格正在使用 system.web.providers。任何人都可以告诉 - 首先如何为用户创建单独的角色,管理员使用实体框架其次如何获取并显示所有具有不同角色的注册用户的列表给管理员。

提前致谢。问候

4

1 回答 1

15
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
    using (var ctx = new UsersContext())
    {
        return View(ctx.UserProfiles.ToList());
    }
}

在视图中:

@using MvcApplication1.Models
@model IEnumerable<UserProfile>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h2>Users list</h2>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var user in Model)
            {
                <tr>
                    <td>@user.UserId</td>
                    <td>@user.UserName</td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

当然,为了能够访问/users/index控制器操作,您首先需要拥有用户和角色。只有管​​理员角色的用户才能调用它。

这里tutorial解释了如何使用迁移来为您的数据库添加一些帐户。

以下是示例迁移配置的样子:

internal sealed class Configuration : DbMigrationsConfiguration<UsersContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(UsersContext context)
    {
        WebSecurity.InitializeDatabaseConnection(
            "DefaultConnection",
            "UserProfile",
            "UserId",
            "UserName", 
            autoCreateTables: true
        );

        if (!Roles.RoleExists("Admin"))
        {
            Roles.CreateRole("Admin");
        }

        if (!WebSecurity.UserExists("john"))
        {
            WebSecurity.CreateUserAndAccount("john", "secret");
        }

        if (!Roles.GetRolesForUser("john").Contains("Admin"))
        {
            Roles.AddUsersToRoles(new[] { "john" }, new[] { "Admin" });
        }
    }
}
于 2012-10-03T12:15:33.257 回答