ใช้วิธีนี้ได้กับโปรเจ็กส์แบบ webapi (โปรเจ็กส์ razor) แต่ยังใช้ไม่ได้กับ Blazor App ต้องรอถึง 5.0 release
- ติดตั้ง dotnet-aspnet-codegenerator
- เพิ่มเพจเกจ Web.CodeGeneration.Design ให้กับโปรเจ็กส์
- Scaffold Identity
- แก้ไขโค๊ด
1.ติดตั้ง dotnet-aspnet-codegenerator
ติดตั้งเครื่องมือก่อน dotnet-aspnet-codegenerator (เป็น global tool)
> dotnet tool install -g dotnet-aspnet-codegenerator You can invoke the tool using the following command: dotnet-aspnet-codegenerator Tool 'dotnet-aspnet-codegenerator' (version '3.1.1') was successfully installed.
การอัพเดท dotnet-aspnet-codegenerator
dotnet tool update -g dotnet-aspnet-codegenerator
2.เพิ่มเพจเกจ Web.CodeGeneration.Design ให้กับโปรเจ็กส์
> dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 3.1.1
3.Scaffold Identity
Scaffold Identity. Include Account.Register, Account.Login, and Account.RegisterConfirmation.
> dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation"
ถ้าลองรันดูจะ error
ลบไฟล์ Areas/Identity/IdentityHostingStartup.cs และ
ลบไฟล์ Areas/Identity/Data/ApplicationDbContext.cs
แล้วแก้ ConnectionStrings ในไฟล์ appsettings.json
ลองรันใหม่จะรันขึ้นละ
4.แก้ไขโค๊ด
Update Areas/Identity/Pages/Account/Register.cshtml.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Demo.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterModel : PageModel
{
public IActionResult OnGet()
{
return RedirectToPage("Login");
}
public IActionResult OnPost()
{
return RedirectToPage("Login");
}
}
}
Update Areas/Identity/Pages/Account/Register.cshtml
@page
@model RegisterModel
@{
ViewData["Title"] = "Go to Login";
}
<h1>@ViewData["Title"]</h1>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
Update Areas/Identity/Pages/Account/Login.cshtml
@*
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
*@
Update the Areas/Identity/Pages/Account/RegisterConfirmation page.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Demo.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
public IActionResult OnGet()
{
return Page();
}
}
}
@page
@model RegisterConfirmationModel
@{
ViewData["Title"] = "Go to Login";
}
<h1>@ViewData["Title"]</h1>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
Update Pages/Shared/_LoginPartial.cshtml
@* <li class="nav-item"> <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a> </li> *@
เสร็จแล้วรันดูก็จะ self register ไม่ได้ละ
เวลาเข้าไปที่ /Identity/Account/Register ก็จะถูก redirect ไปที่ /Identity/Account/Login