1
私の理解では、ユーザーがASP.NET MVCで新しいアカウントを作成すると、これを処理するメソッドは、MVCソリューションのAccountControllerクラスにあるRegisterメソッドになります。これは私のクラスの現在のメソッドがどのように見えるかです:ASP.NET MVCで作成された最初のアカウントのロールを設定するにはどうすればよいですか?
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
しかし、私が気づいたことは、ロールを扱うことに関するコードがないことです。私の目標は、作成される最初のユーザーの役割を設定し、それを管理者ロールにすることです。その後に登録するすべてのユーザーは、その役割と異なる必要があります。このコードで私はどのようにこれにアプローチできますか?
編集:これを達成するには、Seed
メソッドをMigrations\Configuration.cs
にする必要がありますか?もしそうなら、私のシードメソッドはどのように見える必要がありますか?
はい、バックエンドを通じてユーザーと役割を入力します。シーディングは、SSMSでクエリを実行する方法の1つです。 – Jasen
新しく作成されたユーザーにロールを割り当てるには、次の行を追加します。UserManager.AddToRole(user.Id、 "SomeRoleName"); しかし、最初にロールを作成する必要があります。あなたのシードでは同じことをすることができますが、役割を "Admin"に設定してください。 –
ロール名は 'RoleId'を必要としないでしょうから、ユーザーに文字列形式としての役割を追加するのは変ですか?私が気づいたことから、AspNetUserRolesと呼ばれる暫定テーブルは、プロパティ 'UserId'と' RoleId'を使用しています。これを知っている私はロールが既に設定されていると思うので、私はUser(UserIdがassingされている)がRoleIdを割り当てられるべきだと考えました。 @RuardvanElburg – Barrosy