MVC 4 の使用、Simplemembership
企業で使用する Web アプリケーションを構築しているため、すぐに使える MVC 4 テンプレート機能を使用してユーザーが登録できるようにしたくありません。代わりに、管理者のみがアクセスしてユーザーを作成できる [ユーザーの作成] ビューが必要です。登録コントローラーのセキュリティを変更して、現在ログインしているユーザーに既存の登録ビューを使用してユーザーを作成させることができることを望んでいました...サイコロはありません。
これがコントローラーのコードです。テンプレートから変更していません:
// POST: /Account/Register
[HttpPost]
//[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(
model.UserName,
model.Password,
new { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email },
false
);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
現在ログインしているユーザーがこれを介して新しいユーザーを作成しようとすると、エラーが発生します (@ 行 86):
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserProfile_webpages_Membership". The conflict occurred in database "OTIS", table "dbo.webpages_Membership", column 'UserId'.
The statement has been terminated.
Line 84: try
Line 85: {
Line 86: WebSecurity.CreateUserAndAccount(
Line 87: model.UserName,
Line 88: model.Password,
Hwre は UserProfile クラスです
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Email")]
public string Email { get; set; }
}
WebSecurity.CurrentUserID には、現在ログインしているユーザーが入力されています。これが問題の原因であると思います。simplemembership プロバイダーを使用してこれを達成する正しい方法は何ですか?
編集:これを匿名ユーザーの登録を許可するように戻そうとしたので、デバッグ時に WebSecurity.CurrentUserID が -1 になり、それでも同じエラーが発生します。クラスの UserId フィールドが属性 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] で装飾されている場合、重複キーがどのように生成されるのでしょうか?