使用VS Code從零開始構建一個ASP .NET Core Web API 項目


首先需要安裝.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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM