ASP.NET Rest API 详解

一、背景与简介
什么是RESTful API?
REST(Representational State Transfer)是一种架构风格,它利用HTTP协议的标准方法(如GET、POST、PUT、DELETE)来对资源进行操作,RESTful API通过定义清晰的URI和HTTP动词,使得客户端和服务器之间的交互变得简洁和高效。
ASP.NET Core的优势
跨平台:可以在Windows、macOS和Linux上运行。
高性能:共享内存中的缓存机制,提高应用程序的响应速度。
模块化:可以根据需要添加或删除功能,保持应用的灵活性。
先决条件
了解面向对象编程的基本概念。
熟悉C#编程语言。
了解HTTP协议、API端点和JSON格式。
了解关系数据库的工作原理。
二、创建第一个ASP.NET Core Web API项目

安装.NET Core SDK
确保你已经安装了.NET Core SDK,可以从[官方.NET网站](https://dotnet.microsoft.com/download)下载并安装最新版本的.NET Core SDK。
创建Web API项目
打开终端或命令提示符,使用以下命令创建一个新的ASP.NET Core Web API项目:
mkdir src/Supermarket.API cd src/Supermarket.API dotnet new webapi
项目结构
新创建的项目目录结构如下:
src/
Supermarket.API/
bin/
obj/
wwwroot/
Controllers/
Properties/
launchSettings.json
Program.cs
Startup.cs
配置Startup类
在Startup.cs文件中配置服务和中间件:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
三、构建超市产品目录API
创建模型类
在Models文件夹中创建两个模型类:Category和Product。
namespace Supermarket.API.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public string Department { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
}
创建数据上下文类
在Data文件夹中创建数据上下文类SupermarketContext,继承自DbContext。
using Microsoft.EntityFrameworkCore;
namespace Supermarket.API.Data
{
public class SupermarketContext : DbContext
{
public SupermarketContext(DbContextOptions<SupermarketContext> options) : base(options) { }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
}
配置数据库
在Startup.cs文件中配置数据库连接字符串和数据上下文:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SupermarketContext>(opt => opt.UseInMemoryDatabase("SupermarketDB"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
创建控制器类
在Controllers文件夹中创建CategoriesController和ProductsController。
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Supermarket.API.Models;
using Supermarket.API.Data;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace Supermarket.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CategoriesController : ControllerBase
{
private readonly SupermarketContext _context;
public CategoriesController(SupermarketContext context)
{
_context = context;
}
// GET: api/Categories
[HttpGet]
public async Task<ActionResult<IEnumerable<Category>>> GetCategories()
{
return await _context.Categories.ToListAsync();
}
// POST: api/Categories
[HttpPost]
public async Task<ActionResult<Category>> PostCategory(Category category)
{
_context.Categories.Add(category);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCategory", new { id = category.Id }, category);
}
}
}
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly SupermarketContext _context;
public ProductsController(SupermarketContext context)
{
_context = context;
}
// GET: api/Products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.Include(p => p.Category).ToListAsync();
}
// POST: api/Products
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProduct", new { id = product.Id }, product);
}
}
四、测试API接口

使用Postman或类似工具测试API接口,发送GET请求到https://localhost:5001/api/categories以获取所有类别,发送POST请求到https://localhost:5001/api/categories以添加新的类别。
五、集成AutoMapper库
为了简化对象映射,可以集成AutoMapper库,安装AutoMapper NuGet包:
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 7.0.0
然后在Startup.cs中配置AutoMapper:
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
// ... other services ...
}
创建映射配置文件AutoMapperProfile.cs:
using AutoMapper;
using Supermarket.API.Models;
using Supermarket.API.ViewModels; // Assuming you have view models defined here
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Category, CategoryViewModel>();
CreateMap<Product, ProductViewModel>();
// Add more mappings as needed...
}
}
这样,就可以在控制器中使用AutoMapper进行对象映射了。
[HttpGet("{id}")]
public async Task<ActionResult<Category>> GetCategory(int id)
{
var category = await _context.Categories.FindAsync(id);
if (category == null) return NotFound();
var categoryVM = _mapper.Map<CategoryViewModel>(category); // Using AutoMapper for mapping
return Ok(categoryVM);
}
六、归纳与常见问题解答
以上内容就是解答有关“asp.net rest api”的详细内容了,我相信这篇文章可以为您解决一些疑惑,有任何问题欢迎留言反馈,谢谢阅读。