我的第一个ASP.NET Core Web程序
1、新建项目
2、测试启动
3、新建接口和页面
4、测试接口
环境说明:
操作系统:Windows10
开发工具:Visual Studio 2022
框架:.NET 6.0
1、新建项目
项目名称
MockSchoolManagement




创建后如下:

2、测试启动




3、新建接口和页面
学习内容:新建学生接口,可以根据学生ID返回学生信息。
3.1、创建持久化实体类(Model)
在Models下创建学生类Student,代码如下:
public class Student { /** * 主键 */ public int Id { get; set; } /** * 学生姓名 */ public string? Name { get; set; } /** * 专业 */ public string? Major { get; set; } }

3.2、创建持久层
项目下创建文件夹:DataRepositories,然后在此文件夹下创建IStudentRepository接口和他的实现类。
using MockSchoolManagement.Models; namespace MockSchoolManagement.DataRepositories { public interface IStudentRepository { /** * 根据学生ID返回学生信息 */ Student GetStudent(int id); /** * 返回所有学生信息 */ List<Student> GetAll(); } }
using MockSchoolManagement.Models; namespace MockSchoolManagement.DataRepositories { public class StudentRepository : IStudentRepository { private List<Student> _studentList; public StudentRepository() { _studentList=new List<Student>() { new Student(){Id=1,Name="梅梅",Major="计算机科学"}, new Student(){Id=2,Name="mm",Major="计算机应用"}, new Student(){Id=3,Name="krystal",Major="会计专业"}, new Student(){Id=4,Name="克里斯特",Major="绘画"}, new Student(){Id=5,Name="基隆",Major="服装设计"} }; } public List<Student> GetAll() { return _studentList; } public Student GetStudent(int id) { return _studentList.FirstOrDefault(s => s.Id == id); } } }
备注:数据访问层,未链接数据库,使用硬编码实现。

3.3、编写视图(View)
Views下面新建文件夹:Student,在此文件夹下创建Details页面。
@model MockSchoolManagement.Models.Student @{ ViewData["Title"] = "学生页面详请"; } <!DOCTYPE html> <html> <head><title>@ViewData["Title"]</title></head> <body> <table> <tr> <td>Id</td> <td>@Model.Id</td> </tr> <tr> <td>Name</td> <td>@Model.Name</td> </tr> <tr> <td>主修科目</td> <td>@Model.Major</td> </tr> </table> </body> </html>

3.4、编写控制器(Controller)
在Controller文件夹下创建StudentController.cs类,继承Controller类。
定义了Details方法,具体可看代码:
using Microsoft.AspNetCore.Mvc; using MockSchoolManagement.DataRepositories; using MockSchoolManagement.Models; namespace MockSchoolManagement.Controllers { public class StudentController : Controller { private readonly IStudentRepository _studentRepository; public StudentController(IStudentRepository studentRepository) { _studentRepository = studentRepository; } public IActionResult Details(int id) { Student model = _studentRepository.GetStudent(id); return View(model); } } }

3.5、注入数据访问层
使用AddSingleton()向ASP.NET Core依赖注入容器注册StudentRepository类方法。
打开Program.cs,
添加:
builder.Services.AddSingleton<IStudentRepository,StudentRepository>();

4、测试接口
启动项目,根据路由访问规则:/控制器名字/方法名/参数值

在浏览器请求接口:http://localhost:5000/student/details/3

另外说明:
不注入数据访问层,否则会出现下面错误:

InvalidOperationException: Unable to resolve service for type 'MockSchoolManagement.DataRepositories.IStudentRepository' while attempting to activate 'MockSchoolManagement.Controllers.StudentController'.
浙公网安备 33010602011771号