如何使用 ASP.NET Core 8 构建 RESTful API
介绍
现代软件开发通常需要构建 RESTful API。随着 ASP.NET Core 8 的发布,构建健壮且可扩展的 API 变得前所未有的轻松。在本篇博文中,我们将深入探讨如何使用 ASP.NET Core 8 构建 RESTful API,内容涵盖要点、代码示例和个人见解。无论您是经验丰富的开发人员还是刚刚入门的新手,都能从本文中获得宝贵的信息,从而提升您的开发体验。
RESTful API(表述性状态转移)已成为 Web 服务的标准。它们提供了一种简单、可扩展的方式,通过 HTTP 协议公开数据和功能。ASP.NET Core 是一个跨平台、高性能的框架,是构建这些 API 的绝佳选择。随着 ASP.NET Core 8 的发布,我们获得了更多功能和改进,从而提升了开发体验。
如果您对 .NET 开发感兴趣,欢迎访问我们的.NET 开发博客,了解更多最新资讯和最佳实践!
为什么选择 RESTful API?
在深入探讨技术细节之前,我们先花点时间了解一下 RESTful API 如此受欢迎的原因。RESTful API:
-
易于理解和使用:它们使用标准的 HTTP 方法和状态代码,因此各个级别的开发人员都可以使用它们。
-
支持广泛的客户端:从 Web 应用程序到移动应用程序和物联网设备,几乎任何可以发出 HTTP 请求的客户端都可以使用 RESTful API。
-
提倡无状态通信:客户端的每个请求都包含处理该请求所需的所有信息,从而实现可扩展且具有弹性的系统。
-
鼓励良好的设计实践:使用 REST 原则,您可以设计出简洁、直观且易于维护和发展的 API。
ASP.NET Core 8 入门指南
要开始使用 ASP.NET Core 8 构建 RESTful API,您需要设置开发环境。请确保已安装以下软件:
- .NET 8 SDK
- Visual Studio 或 Visual Studio Code
- 用于测试的现代网络浏览器
创建一个新的 ASP.NET Core 项目
打开终端或命令提示符,运行以下命令创建一个新的 ASP.NET Core 项目:
dotnet new webapi -n MyApi
cd MyApi
此命令会创建一个名为 MyApi 的新 ASP.NET Core Web API 项目,并导航到项目目录。请在您喜欢的 IDE 中打开该项目。
项目结构
您的项目将采用以下结构:
MyApi
├── Controllers
│ └── WeatherForecastController.cs
├── Program.cs
├── Startup.cs
└── MyApi.csproj
Controllers 文件夹包含默认的 WeatherForecastController。我们稍后会创建自己的控制器。
构建您的第一个 API 端点
让我们创建一个简单的 API 端点,用于返回产品列表。首先定义一个产品模型。
定义产品模型
创建一个名为 Models 的新文件夹,并在其中添加一个名为 Product.cs 的文件,内容如下:
namespace MyApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
创建产品控制器
接下来,如果 Controllers 文件夹不存在,则创建一个,并在其中添加 ProductsController.cs 文件:
using Microsoft.AspNetCore.Mvc;
using MyApi.Models;
using System.Collections.Generic;
using System.Linq;
namespace MyApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static readonly List<Product> Products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M },
new Product { Id = 2, Name = "Smartphone", Price = 499.99M }
};
[HttpGet]
public ActionResult<IEnumerable<Product>> GetProducts()
{
return Ok(Products);
}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public ActionResult<Product> CreateProduct(Product product)
{
product.Id = Products.Count + 1;
Products.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product updatedProduct)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
product.Name = updatedProduct.Name;
product.Price = updatedProduct.Price;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
Products.Remove(product);
return NoContent();
}
}
}
解释
- [ApiController] 和 [Route] 属性:这些属性指定此类为 API 控制器,并定义控制器中所有操作的基本路由。
- GET /api/products:返回所有产品的列表。
- GET /api/products/{id}:根据 ID 返回单个产品。
- POST /api/products:创建新产品。
- PUT /api/products/{id}:更新现有产品。
- DELETE /api/products/{id}:根据 ID 删除产品。
运行 API
要运行您的 API,请使用以下命令:
dotnet run
打开浏览器并访问https://localhost:5001/api/products查看产品列表。
高级功能和最佳实践
现在我们有了基本的 API,让我们来探索一些高级功能和最佳实践,使其更加健壮和易于维护。
使用 Entity Framework Core
在实际应用中,通常会使用数据库来存储数据。Entity Framework Core (EF Core) 是一个优秀的 ORM(对象关系映射器),用于在 .NET 中处理数据库。
设置 EF Core
首先,将 EF Core 包添加到您的项目中:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
配置 DbContext
创建一个名为“Data”的文件夹,并在其中添加一个名为“AppDbContext.cs”的文件:
using Microsoft.EntityFrameworkCore;
using MyApi.Models;
namespace MyApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
}
更新 Program.cs 文件以配置 DbContext:
using Microsoft.EntityFrameworkCore;
using MyApi.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
在 appsettings.json 文件中添加连接字符串:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyApiDb;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
更新产品控制器
更新 ProductsController 以使用 EF Core:
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyApi.Data;
using MyApi.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyApi.Controllers
{
[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();
}
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
[HttpPost]
public async Task<ActionResult<Product>> CreateProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateProduct(int id, Product updatedProduct)
{
if (id != updatedProduct.Id)
{
return BadRequest();
}
_context.Entry(updatedProduct).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!_context.Products.Any(e => e.Id == id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
}
}
实施验证
为确保数据完整性,验证输入至关重要。ASP.NET Core 提供了内置的验证机制。
向产品模型添加数据注释:
using System.ComponentModel.DataAnnotations;
namespace MyApi.Models
{
public class Product
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Range(0.01, 10000.00)]
public decimal Price { get; set; }
}
}
验证错误由 ASP.NET Core 自动处理并返回给客户端。
结论
使用 ASP.NET Core 8 构建 RESTful API 是一项极具成就感的工作。凭借所有最新特性和改进,您可以为当今的应用程序创建强大且可扩展的 API。从设置项目和定义端点,到利用 Entity Framework Core 和实现验证,我们涵盖了入门所需的基础知识。
记住,你的编程之旅并未就此结束。继续学习,提升技能,随时向社区提问或寻求帮助。祝你编程愉快!
在构建 API 的过程中,你遇到过哪些挑战?分享你的经验,一起学习吧!
如有任何疑问或需要进一步帮助,请随时联系我们。您的反馈和经验有助于我们改进这段旅程,让每个人都能从中受益。
文章来源:https://dev.to/wirefuture/how-to-build-restful-apis-with-aspnet-core-8-j5如果您对 .NET 开发感兴趣,欢迎访问我们的.NET 开发博客,了解更多最新资讯和最佳实践!