# ASP.NET Core的WebApi和EF Core該怎么樣入門
## 前言
ASP.NET Core是微軟推出的跨平臺Web開發框架,結合Entity Framework Core(EF Core)可以快速構建數據驅動的Web API。本文將帶你從零開始掌握這兩個技術的核心用法。
## 一、環境準備
### 1. 安裝開發工具
- [Visual Studio 2022](https://visualstudio.microsoft.com/)(社區版免費)
- 或 [VS Code](https://code.visualstudio.com/) + .NET SDK
- 推薦安裝".NET Core跨平臺開發"工作負載
### 2. 驗證環境
```bash
dotnet --version
# 應顯示6.0或更高版本
dotnet new webapi -n MyFirstApi
cd MyFirstApi
Controllers/ # API控制器
appsettings.json # 配置文件
Program.cs # 主入口文件
dotnet run
訪問 https://localhost:5001/weatherforecast
應返回JSON數據
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
// Models/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// Data/AppDbContext.cs
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
public DbSet<Product> Products { get; set; }
}
// appsettings.json
"ConnectionStrings": {
"Default": "Server=(localdb)\\mssqllocaldb;Database=MyApiDb;Trusted_Connection=True;"
}
// Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
dotnet ef migrations add InitialCreate
dotnet ef database update
// Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
public class ProductDto
{
public string Name { get; set; }
public decimal Price { get; set; }
}
dotnet add package Swashbuckle.AspNetCore
// Program.cs
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
// 在控制器中注入ILogger
private readonly ILogger<ProductsController> _logger;
// 記錄日志
_logger.LogInformation("Getting all products");
dotnet publish -c Release -o ./publish
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
COPY ./publish .
ENTRYPOINT ["dotnet", "MyFirstApi.dll"]
通過本文,你已經掌握了: 1. 創建ASP.NET Core WebApi項目 2. 配置EF Core進行數據訪問 3. 實現基本的CRUD操作 4. 一些生產環境實用技巧
建議下一步: - 學習ASP.NET Core中間件 - 探索EF Core高級特性 - 實踐身份認證與授權 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。