[Authorize(Roles = "Admin")]
public ActionResult Index()
{
using (var ctx = new UsersContext())
{
return View(ctx.UserProfiles.ToList());
}
}
và trong giao diện:
@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>
Tất nhiên để có thể truy cập vào hành động /users/index
điều khiển bạn cần phải đầu tiên có người dùng và vai trò. Chỉ người dùng trong vai trò Quản trị mới có thể gọi nó.
Đây là số tutorial
giải thích cách bạn có thể sử dụng di chuyển để tạo cơ sở dữ liệu cho một số tài khoản.
Sau đây là cách cấu hình di cư mẫu có thể trông giống như:
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" });
}
}
}
Nguồn
2012-10-03 12:15:33
tôi đã có thêm @model IEnumerable theo quan điểm của tôi để có được điều này để làm việc với các tiêu chuẩn (mô hình => mô hình .Username). 1 vì điều này giúp tôi đi đúng hướng. Không chính xác chắc chắn sự khác biệt là gì. Tôi sẽ nghĩ rằng nếu nó tìm thấy UserProfile nó sẽ không cần mô hình đầy đủ cộng với nó có tuyên bố sử dụng. –
Xaxum
Đề xuất có thể là dòng sau đây để kiểm tra xem người dùng có chứa một vai trò không ... if (! Roles.IsUserInRole ("john", "Admin")) –