.NET6 WEBAPI搭建步骤
# .NET6 WEBAPI搭建步骤
- 安装相关NuGet包
Install-Package Microsoft.EntityFrameworkCore
Install-Package MySql.EntityFrameworkCore //如果是mysql
Install-Package Microsoft.EntityFrameworkCore.SqlServer //如果是mssql
1
2
3
4
2
3
4
- 创建上下文链接类
using AntVue3Demo.Models;
using Microsoft.EntityFrameworkCore;
public class DbEntitys : DbContext
{
/// <summary>
/// 配置连接字符串,每次访问数据库之前会自动执行此方法,在这里配置连接字符串
/// 相当于连接前事件
/// 使用 IOC 注入的方式不实现此方法
/// </summary>
/// <param name="builder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
// 连接字符串
string ConnString = "Server=101.33.219.205;Database=AntVue3DemoDB;User ID=sa;Password=memeda999;";
// 连接SqlServer
builder.UseSqlServer(ConnString);
// 连接MySql
//builder.UseMySql(ConnString);
}
/// <summary>
/// 默认构造函数 使用方法与原来一样
/// </summary>
public DbEntitys() : base() { }
/// <summary>
/// 通过IOC
/// </summary>
/// <param name="options"></param>
public DbEntitys(DbContextOptions<DbEntitys> options) : base(options)
{ }
#region 表映射
public virtual DbSet<Tabs> Tab1 { get; set; }
#endregion
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
3.根据模型映射建库(CodeFist生成库)
Install-Package Microsoft.EntityFrameworkCore.Tools
Add-Migration InitialCreate(名称可自定义)
Update-Database
1
2
3
4
2
3
4
或手动创建Model映射表类,并体现在上下文链接类中
4.Program.cs文件的跨域配置
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//跨域配置
builder.Services.AddCors(options =>
{
options.AddPolicy
(name: "kuayu",
builde =>
{
builde.WithOrigins("*", "*", "*")
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}
);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.UseCors("kuayu");
app.MapControllers();
app.Run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
5.在需要跨域的控制器文件中加入
[EnableCors("kuayu")]
[Route("api/[controller]")]
1
2
3
2
3
上次更新: 2024/01/18, 10:14:14