3. 创建控制器
接口控制器就是客户端访问的入口,与接口服务对应,一个四个接口控制器,如下所示:
学生控制器StudentController
学生控制器封装学生操作的服务,包括学生的增删改查的接口,如下所示:
1. namespace SIMS.WebApi.Controllers 2. { 3. /// <summary> 4. /// 学生控制器 5. /// </summary> 6. [Route("api/[controller]/[action]")] 7. [ApiController] 8. public class StudentController : ControllerBase 9. { 10. private readonly ILogger<StudentController> logger; 11. 12. private readonly IStudentAppService studentAppService; 13. 14. public StudentController(ILogger<StudentController> logger, IStudentAppService studentAppService) { 15. this.logger = logger; 16. this.studentAppService = studentAppService; 17. } 18. 19. /// <summary> 20. /// 学生列表,带分页 21. /// </summary> 22. /// <param name="pageNum"></param> 23. /// <param name="pageSize"></param> 24. /// <param name="no"></param> 25. /// <param name="name"></param> 26. /// <returns></returns> 27. [HttpGet] 28. public PagedRequest<StudentEntity> GetStudents(int pageNum, int pageSize,string? no = null ,string? name=null ) { 29. return studentAppService.GetStudents(no,name, pageNum, pageSize); 30. } 31. 32. /// <summary> 33. /// 查询某一班级的学生列表 34. /// </summary> 35. /// <param name="classId"></param> 36. /// <returns></returns> 37. [HttpGet] 38. public PagedRequest<StudentEntity> GetStudentsByClasses(int classId) { 39. return studentAppService.GetStudentsByClasses(classId); 40. } 41. 42. /// <summary> 43. /// 获取学生信息 44. /// </summary> 45. /// <param name="id"></param> 46. /// <returns></returns> 47. [HttpGet] 48. public StudentEntity GetStudent(int id) { 49. return studentAppService.GetSudent(id); 50. } 51. 52. /// <summary> 53. /// 新增学生 54. /// </summary> 55. /// <param name="student"></param> 56. /// <returns></returns> 57. [HttpPost] 58. public int AddStudent(StudentEntity student) 59. { 60. return studentAppService.AddStudent(student); 61. } 62. 63. /// <summary> 64. /// 修改学生 65. /// </summary> 66. /// <param name="student"></param> 67. /// <returns></returns> 68. [HttpPut] 69. public int UpdateStudent(StudentEntity student) { 70. return studentAppService.UpdateStudent(student); 71. } 72. 73. /// <summary> 74. /// 删除学生 75. /// </summary> 76. /// <param name="id"></param> 77. [HttpDelete] 78. public int DeleteStudent(int id) 79. { 80. return studentAppService.DeleteStudent(id); 81. } 82. } 83. }
班级控制器ClassesController
班级控制器是对班级接口服务的封装,包含对班级的增删改查,如下所示:
1. namespace SIMS.WebApi.Controllers 2. { 3. /// <summary> 4. /// 班级控制器 5. /// </summary> 6. [Route("api/[controller]/[action]")] 7. [ApiController] 8. public class ClassesController : ControllerBase 9. { 10. private readonly ILogger<ClassesController> logger; 11. 12. private readonly IClassesAppService classesAppService; 13. 14. public ClassesController(ILogger<ClassesController> logger, IClassesAppService classesAppService) 15. { 16. this.logger = logger; 17. this.classesAppService = classesAppService; 18. } 19. 20. /// <summary> 21. /// 获取班级信息 22. /// </summary> 23. /// <param name="id"></param> 24. /// <returns></returns> 25. [HttpGet] 26. public ClassesEntity GetClasses(int id) 27. { 28. return classesAppService.GetClasses(id); 29. } 30. 31. /// <summary> 32. /// 获取班级列表 33. /// </summary> 34. /// <param name="id"></param> 35. /// <returns></returns> 36. [HttpGet] 37. public PagedRequest<ClassesEntity> GetClassess(string? dept, string? grade, int pageNum, int pageSize) 38. { 39. return classesAppService.GetClassess(dept,grade,pageNum,pageSize); 40. } 41. 42. /// <summary> 43. /// 新增班级 44. /// </summary> 45. /// <param name="classes"></param> 46. /// <returns></returns> 47. [HttpPost] 48. public int AddClasses(ClassesEntity classes) 49. { 50. return classesAppService.AddClasses(classes); 51. } 52. 53. /// <summary> 54. /// 修改班级 55. /// </summary> 56. /// <param name="classes"></param> 57. /// <returns></returns> 58. [HttpPut] 59. public int UpdateClasses(ClassesEntity classes) 60. { 61. return classesAppService.UpdateClasses(classes); 62. } 63. 64. /// <summary> 65. /// 删除班级 66. /// </summary> 67. /// <param name="id"></param> 68. [HttpDelete] 69. public int DeleteClasses(int id) 70. { 71. return classesAppService.DeleteClasses(id); 72. } 73. } 74. }
注意:其他控制器,暂是代码不全,暂不贴示。
通过以上示例可以看出,接口服务依赖DataContext,控制器依赖接口服务,那么如果要使程序得以运行,就要逐层创建对象,并传递对象实体。手工创建非常不方便,所以就需要引入Autofac进行自动注入,如下所示:
4. 注入DataContext
在Program中,通过构造器,注入DataContext,如下所示:
builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
注意:Default为appsetting.json中配置的数据库连接字符串。如下所示:
1. { 2. "Logging": { 3. "LogLevel": { 4. "Default": "Information", 5. "Microsoft.AspNetCore": "Warning" 6. } 7. }, 8. "ConnectionStrings": { 9. "Default": "Server=localhost;Database=SIMS;Trusted_Connection=True;User Id=sa;Password=abc123" 10. }, 11. "AllowedHosts": "*" 12. }
5. 配置Autofac框架
Autoface框架可以实现接口的自动注入,减少繁琐的人工操作,如下所示:
1. // 以下是autofac依赖注入 2. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); 3. builder.Host.ConfigureContainer<ContainerBuilder>(builder => 4. { // 注入Service程序集 5. string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; 6. builder.RegisterAssemblyTypes(Assembly.Load(assemblyName)) 7. .AsImplementedInterfaces() 8. .InstancePerDependency(); 9. });
Program中全部代码,如下所示:
1. using Autofac; 2. using Autofac.Extensions.DependencyInjection; 3. using Microsoft.EntityFrameworkCore; 4. using SIMS.WebApi; 5. using SIMS.WebApi.Data; 6. using SIMS.WebApi.Services.Student; 7. using System.Configuration; 8. using System.Reflection; 9. 10. var builder = WebApplication.CreateBuilder(args); 11. 12. // Add services to the container. 13. 14. builder.Services.AddControllers(); 15. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 16. builder.Services.AddEndpointsApiExplorer(); 17. builder.Services.AddSwaggerGen(); 18. builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))); 19. // 以下是autofac依赖注入 20. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); 21. builder.Host.ConfigureContainer<ContainerBuilder>(builder => 22. { // 注入Service程序集 23. string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; 24. builder.RegisterAssemblyTypes(Assembly.Load(assemblyName)) 25. .AsImplementedInterfaces() 26. .InstancePerDependency(); 27. }); 28. var app = builder.Build(); 29. 30. // Configure the HTTP request pipeline. 31. if (app.Environment.IsDevelopment()) 32. { 33. app.UseSwagger(); 34. app.UseSwaggerUI(); 35. } 36. 37. app.UseHttpsRedirection(); 38. 39. app.UseAuthorization(); 40. 41. app.MapControllers(); 42. 43. app.Run();
6. 代码结构
WebApi中代码结构如下所示:
7. 运行WebApi服务
经过以上步骤的操作,Api接口已经基本搭建完成,将SIMS.WebApi作为启动项目,运行VS,如下所示:
8. 接口测试
默认情况下WebApi继承了Swagger,可以进行简单的测试,以/api/Classes/GetClasses为例,输入班级ID,就可查询班级信息,如下所示:
以上就是本次的主要内容,包含数据库的基本操作和WebApi接口的创建流程,旨在抛转引玉,一起学习,共同进步。
备注
上邪【作者】佚名 【朝代】汉
上邪,我欲与君相知,长命无绝衰。
山无陵,江水为竭。
冬雷震震,夏雨雪。
天地合,乃敢与君绝。