标签:Core Code -- public test add API dotnet Microsoft
首先需要安装.NET SDK 6.0 下载地址:Download .NET 6.0 (Linux, macOS, and Windows) (microsoft.com)
在VS Code终端运行指令创建项目
dotnet new webapi -o test进入项目所在的文件夹
cd test
重启VS Code
code -r ../test
继续在终端运行以下指令: 添加EF Core工具包 dotnet add package Microsoft.EntityFrameworkCore --prerelease dotnet add package Microsoft.EntityFrameworkCore.Tools --prerelease dotnet add package Microsoft.EntityFrameworkCore.Design --prerelease dotnet add package Microsoft.EntityFrameworkCore.SqlServer --prerelease 添加代码生成工具 dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --prerelease dotnet tool install -g dotnet-aspnet-codegenerator --version 6.0.1 信任HTTPS开发证书 dotnet dev-certs https --trust 此处弹出的窗口直接点确定
以上步骤结束后,下面就可以开始进行开发了。
新建Models文件夹
mkdir Models
在Models文件夹下添加实体类 UserModel.cs
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace test.Models; [Table("User")] public class UserModel { [Key] public long ID { get; set; } [Required] [MaxLength(50)] [Column("UserName")] public string? UserName { get; set; } }
新建数据库上下文 TestDbContext.cs
using Microsoft.EntityFrameworkCore; using test.Models; namespace test; public class TestDbContext : DbContext { public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } public DbSet<UserModel> UserModels { get; set; } = null!; }
在Program.cs中进行依赖注入
builder.Services.AddDbContext<TestDbContext>(opt => opt.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Test;MultipleActiveResultSets=true;Trusted_Connection=True;"));
在终端执行以下指令,自动生成Controller
dotnet aspnet-codegenerator controller -name UserController -async -api -m UserModel -dc TestDbContext -outDir Controllers
可以看到,此时项目里的Controllers文件夹下自动生成了 UserController.cs 文件,里面自动生成了基本的增删改查方法。
执行以下指令,自动生成数据库
dotnet ef migrations add InitialCreate
dotnet ef database update
成功后,运行项目。
dotnet watch run
此时会自动弹出swagger页面
可以开始测试了。
以上就是全部内容。
参考微软官方教程:教程:使用 ASP.NET Core 创建 Web API | Microsoft Docs
标签:Core,Code,--,public,test,add,API,dotnet,Microsoft 来源: https://www.cnblogs.com/code-porter-233/p/16024322.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。