我已经使用CLI在Mac上开始了我的dotnet core MVC项目,但是没有添加身份验证功能。现在我想添加此功能。到目前为止,我唯一知道的选项是通过
dotnet new mvc --auth
有没有更好的方法为现有项目添加身份验证?我希望有一个“dotnet new”命令。
我已经使用CLI在Mac上开始了我的dotnet core MVC项目,但是没有添加身份验证功能。现在我想添加此功能。到目前为止,我唯一知道的选项是通过
dotnet new mvc --auth
有没有更好的方法为现有项目添加身份验证?我希望有一个“dotnet new”命令。
1) 如果您之前还没有安装ASP.NET Core脚手架程序,请现在进行安装:
dotnet tool install -g dotnet-aspnet-codegenerator
2) 将Microsoft.VisualStudio.Web.CodeGeneration.Design包引用添加到项目(*.csproj)文件中。在项目目录中运行以下命令:
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet restore
3) 运行以下命令以列出Identity脚手架选项:
dotnet aspnet-codegenerator identity -h
4) 在项目文件夹中,使用您想要的选项运行 Identity scaffolder。例如,要设置带有默认 UI 和最少数量的文件的身份验证,请运行以下命令:
4) 在项目文件夹中运行 Identity scaffolder,并使用您所需的选项。例如,若要使用默认UI和最少数量的文件设置身份验证,请运行以下命令:
dotnet aspnet-codegenerator identity --useDefaultUI
5) 生成的 Identity 数据库代码需要 Entity Framework Core 迁移。创建一个迁移并更新数据库。例如,运行以下命令:
dotnet ef migrations add CreateIdentitySchema
dotnet ef database update
6)在调用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();
}
}
您需要通过VS Code中的CLI添加此NuGet包:
dotnet add package Microsoft.AspNetCore.Identity
如果你想要标准的用户界面页面,你可以安装这个包,它包含了所有嵌入式内容:
dotnet add package Microsoft.AspNetCore.Identity.UI
appsettings.json
中最终如下所示: "AuthDbContextConnection": "Data Source=xxx.xxx.xxx.xxx,10008;Initial Catalog=dbName;Persist Security Info=True;User ID=sqluser;Password=sqlpassword"
xxx.xxx.xxx.xxx
在这里代替IP地址。
我无法安装Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
,所以我去了这里的页面,并为我的项目(.NET Core 3.x)安装了最新版本此处。所以我已经安装了包:
Install-Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore -Version 3.1.10
Add-Migration CreateIdentitySchema -Context AuthDbContext
Update-Database 20201217102436_InitialCreate -Context AuthDbContext
and than
Update-Database 20201218083037_CreateIdentitySchema -Context AuthDbContext
这样做成功了。表已经在 MS SQL Server 中创建。