选择ASP.NET Core Web应用程序
项目名称和路径
项目类型选择 API
ASP.NET Core 版本选择 3.1
点击创建,等待项目创建
删除原本的代码,配置新的
{
"ConnectionStrings": {
"Conn": "Server=.;Database=TEST;Uid=sa;Pwd=123456;"
}
}
创建 Entity 文件夹,创建 App_Admin.cs 实体类
using System;
namespace AppManager.Api.Entity
{
public class App_Admin
{
public int Id {
get; set; }
public string UserName {
get; set; }
public string Password {
get; set; }
public DateTime CreateTime {
get; set; }
public string Admin {
get; set; }
public short Status {
get; set; }
public string Avatar {
get; set; }
public string City {
get; set; }
}
}
右键依赖性 > 管理 NuGet 程序包
安装两个包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
创建类:AppDbContext 继承:DbContext
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppManager.Api.Entity
{
///
/// EF连接数据库上下文类
///
public class AppDbContext:DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<App_Admin> App_Admin {
get; set; }
}
}
//注入数据库
services.AddDbContext<AppDbContext>(options =>
//指定sqlserver数据库(读取连接字符串)
options.UseSqlServer(Configuration.GetConnectionString("Conn"))
);
//注入跨域
services.AddCors(options =>
{
options.AddPolicy("CorePolicy",
//允许任何方法
builder => builder.AllowAnyMethod()
//允许任何的源
.SetIsOriginAllowed(_ => true)
//运行任何的请求头
.AllowAnyHeader()
.AllowCredentials());
});
//跨域中间件
app.UseCors("CorePolicy");
//注入缓存
services.AddMemoryCache();
//注入httpContext
services.AddHttpContextAccessor();
//设置 httpContext 生命周期
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppManager.Api.Extensions
{
///
/// 上下文用户对象
///
public class AuthContextUser
{
public int Id {
get; set; }
public string UserName {
get; set; }
public string Avator {
get; set; }
public int Status {
get; set; }
}
}
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace AppManager.Api.Extensions
{
public static class AuthContextService
{
private static IHttpContextAccessor _context;
public static void Configuration(IHttpContextAccessor httpContextAccessor)
{
_context = httpContextAccessor;
}
//上下文
public static HttpContext Current => _context.HttpContext;
public static AuthContextUser CurrentUser
{
get