新規ユーザー登録
AccountViewModels.vbのRegisterViewModelの修正
リスト10-3及び??演算子(null合体演算子 C#)
リスト10-3の2で実行時エラー(NullReferenceException)の場合、App_Start/Startup.Auth.vbを追加修正
1.AccountViewModels.vbのRegisterViewModel
'※UserNameにはEmailを利用する仕様
Public Class RegisterViewModel
<Required>
<EmailAddress>
<Display(name:="電子メール")>
Public Property Email As String
<Required>
<StringLength(100, ErrorMessage:="{0} の長さは、{2} 文字以上である必要があります。", MinimumLength:=6)>
<DataType(DataType.Password)>
<Display(Name:="パスワード")>
Public Property Password As String
<DataType(DataType.Password)>
<Display(Name:="パスワードの確認入力")>
<Compare("Password", ErrorMessage:="パスワードと確認のパスワードが一致しません。")>
Public Property ConfirmPassword As String
End Class
2.リスト10-3 (Importsステートメントとコンストラクター及びプロパティ部分も併記)
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Security.Claims
Imports System.Threading.Tasks
Imports System.Web
Imports System.Web.Mvc
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Imports Owin
<Authorize>
Public Class AccountController
Inherits Controller
Private _userManager As ApplicationUserManager
Public Sub New()
End Sub
Public Sub New(manager As ApplicationUserManager)
UserManager = manager
End Sub
Public Property UserManager As ApplicationUserManager
Get
'C# null合体演算子 return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Return If(IsNothing(_userManager), HttpContext.GetOwinContext().GetUserManager(Of ApplicationUserManager), _userManager)
End Get
Set(value As ApplicationUserManager)
_userManager = value
End Set
End Property
・・・中略・・・
'
' GET: /Account/Register
<AllowAnonymous>
Public Function Register() As ActionResult
Return View()
End Function
'
' POST: /Account/Register
<HttpPost>
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Async Function Register(model As RegisterViewModel) As Task(Of ActionResult)
If ModelState.IsValid Then
' ユーザーにサインインする前にローカル ログインを作成します。
Dim user = New ApplicationUser() With {.UserName = model.Email, .Email = model.Email}
Dim result As IdentityResult = Await UserManager.CreateAsync(user, model.Password)
If result.Succeeded Then
Await SignInAsync(user, isPersistent:=False)
Return RedirectToAction("Index", "Home")
Else
AddErrors(result)
End If
End If
' ここで問題が発生した場合はフォームを再表示します
Return View(model)
End Function
・・・中略・・・
End Function
3.App_Start/Startup.Auth.vb(太字2行追加)
・・・中略・・・
Partial Public Class Startup
' 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください
Public Sub ConfigureAuth(app As IAppBuilder)
app.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
app.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
' アプリケーションが Cookie を使用して、サインインしたユーザーの情報を格納できるようにします
・・・中略・・・