ASP.NET Core Web API:移除示例并自定义HTTP Get请求与响应
移除默认WeatherForecast示例
- 删除项目根目录下的
WeatherForecast.cs类文件 - 删除Controllers文件夹中的
WeatherForecastController.cs文件 - 若启用了Swagger,无需额外配置,重启项目后示例接口会自动从文档中消失
自定义HTTP Get请求基础模板
1. 创建响应模型
在项目中新建Models文件夹,添加自定义响应类(以用户信息为例):
namespace YourProjectName.Models; // 自定义响应模型,用于封装接口返回的数据 public class UserInfo { public int Id { get; set; } public string Name { get; set; } = string.Empty; public string Email { get; set; } = string.Empty; }
2. 编写自定义API控制器
在Controllers文件夹下新建控制器类(比如UserController.cs):
using Microsoft.AspNetCore.Mvc; using YourProjectName.Models; namespace YourProjectName.Controllers; // [ApiController] 自动处理模型验证、路由绑定等Web API特性 [ApiController] // 定义接口基础路由:api/控制器名(此处为api/User) [Route("api/[controller]")] public class UserController : ControllerBase { // 模拟数据源,实际项目可替换为数据库查询逻辑 private readonly List<UserInfo> _mockUsers = new() { new UserInfo { Id = 1, Name = "张三", Email = "zhangsan@example.com" }, new UserInfo { Id = 2, Name = "李四", Email = "lisi@example.com" } }; // 无参数Get请求:返回所有用户数据 [HttpGet] public ActionResult<IEnumerable<UserInfo>> GetAllUsers() { // Ok() 会返回200状态码和序列化后的模型数据 return Ok(_mockUsers); } // 带路由参数的Get请求:根据ID返回单个用户 [HttpGet("{id}")] public ActionResult<UserInfo> GetUserById(int id) { var targetUser = _mockUsers.FirstOrDefault(u => u.Id == id); if (targetUser == null) { // NotFound() 返回404状态码,表示资源不存在 return NotFound(); } return Ok(targetUser); } }
3. 前端请求示例(JavaScript)
// 请求所有用户数据 fetch('/api/User') .then(res => res.json()) .then(data => console.log('所有用户:', data)) .catch(err => console.error('请求失败:', err)); // 请求ID为1的用户数据 fetch('/api/User/1') .then(res => { if (!res.ok) throw new Error('用户不存在'); return res.json(); }) .then(data => console.log('目标用户:', data)) .catch(err => console.error('请求失败:', err));
4. 接口测试
- 直接在浏览器地址栏访问
https://localhost:{你的项目端口}/api/User,可查看返回的JSON数据 - 用Postman、Insomnia等工具测试带参数的请求,比如
https://localhost:{端口}/api/User/1
内容的提问来源于stack exchange,提问作者Rafay Shams
相关产品推荐
相关产品推荐

