Asp.net-Mvc
如何將 ASP.NET Core 標識添加到現有的 Core mvc 項目?
我已經使用 CLI 在 Mac 上啟動了沒有身份的 dotnet core mvc 項目,現在我想添加此功能。到目前為止,我知道的唯一選擇是通過以下方式創建一個新項目
dotnet new mvc --auth有沒有更好的方法來為現有項目添加身份?我希望有一個“dotnet new”命令。
您需要通過 CLI 在 VS Code 中添加此 NuGet 包:
dotnet add package Microsoft.AspNetCore.Identity如果你想要標準的 UI 頁面,你可以安裝這個包含所有嵌入內容的包:
dotnet add package Microsoft.AspNetCore.Identity.UI
根據docs.microsoft.com ,您可以使用aspnet-codegenerator將身份建構到現有的 MVC 項目中。
- 如果您之前沒有安裝過 ASP.NET Core 腳手架,請立即安裝:
dotnet tool install -g dotnet-aspnet-codegenerator
- 將 Microsoft.VisualStudio.Web.CodeGeneration.Design 的包引用添加到項目 (*.csproj) 文件中。在項目目錄中執行以下命令:
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design dotnet restore
- 執行以下命令列出 Identity 腳手架選項:
dotnet aspnet-codegenerator identity -h
- 在項目文件夾中,使用所需選項執行 Identity 腳手架。例如,要使用預設 UI 和最少文件數設置身份,請執行以下命令:
dotnet aspnet-codegenerator identity --useDefaultUI
- 生成的 Identity 數據庫程式碼需要 Entity Framework Core Migrations。創建遷移並更新數據庫。例如,執行以下命令:
dotnet ef migrations add CreateIdentitySchema dotnet ef database update6)在UseStaticFiles之後呼叫UseAuthentication:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAuthentication(); // <-- add this line app.UseMvcWithDefaultRoute(); } }