[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
コントローラのアクションにアクセスできるようにするためです。 Adminロールのユーザーのみが起動できます。
ここには、データベースをいくつかのアカウントでシードするために移行を使用する方法を説明する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" });
}
}
}
私はこれが標準(モデル=>モデルで動作するように取得するために私の見解では@modelのIEnumerableを追加する必要がありました。ユーザー名)。これは正しい軌道に乗ったからです。違いが何であるか正確には分かりません。 UserProfileが見つかると、それは完全なモデルとそれにusingステートメントが必要ないと思います。 –
Xaxum
ユーザーにロールが含まれているかどうかを確認するために、おそらく次の行が示唆されます... if(!Roles.IsUserInRole( "john"、 "Admin")) –