webapi core2.1 Identity.EntityFramework Core进行配置和操作数据 (一)没什么用

时间:2023-02-06 19:12:24

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&tabs=visual-studio%2Caspnetcore2x  的实践

微软无api 的 identity 配置,专门写一篇关于 vs code 的配置

dotnet new webapi -o Demo
cd demo
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

Startup.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Demo.Data;

->ConfigureServices

 services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();

Data->ApplicationDbContext.cs 新建文件夹及文件

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; namespace Demo.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}

appsettings.json 加入数据库连接

  "ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-ids-3D54E4B2-38C1-466C-A12F-E9CCF493B11B;Trusted_Connection=True;MultipleActiveResultSets=true"
},

最后生成编译,

生成数据库映射表

更新数据库

dotnet build
dotnet ef migrations add Initial -o Data/Migrations
dotnet ef database update