2019-08-23 11:32:45
1. 项目创建
1.1 安装
下载.NETCORE SDK 进行安装
下载NETCORE RUNTIME进行安装.
下载Runtime & Hosting Bundle进行安装
下载地址:https://dotnet.microsoft.com/download/dotnet-core
微软的安装在windows方面很简单,基本就是一键安装.
1.2 开发工具
VisualStudio 2019
1.3建立项目工程
点击文件创建项目,出现如下图示
选择画红圈部分,接着出现如下图示
1.4生成数据库实体,并用EF迁移数据库(上一篇中已讲到)
2. 生成API控制器
2.1 在Controllers文件夹上右键,点击添加,选择新搭建的基架项目
2.2 选择要添加的类型
2.3 选择数据库上下文类,模型类点击添加
项目将自动添加依赖 Microsoft.AspNetCore.Razor.Design
2.4 控制器的增删改查方法将自动生成
namespace ContosoUniversity.Controllers { [Route("api/[controller]")] [ApiController] public class CoursesController : ControllerBase { private readonly SchoolContext _context; public CoursesController(SchoolContext context) { _context = context; } // GET: api/Courses [HttpGet] public async Task<ActionResult<IEnumerable<Course>>> GetCourses() { return await _context.Courses.ToListAsync(); } // GET: api/Courses/5 [HttpGet("{id}")] public async Task<ActionResult<Course>> GetCourse(int id) { var course = await _context.Courses.FindAsync(id); if (course == null) { return NotFound(); } return course; } // PUT: api/Courses/5 [HttpPut("{id}")] public async Task<IActionResult> PutCourse(int id, Course course) { if (id != course.CourseID) { return BadRequest(); } _context.Entry(course).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CourseExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Courses [HttpPost] public async Task<ActionResult<Course>> PostCourse(Course course) { _context.Courses.Add(course); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (CourseExists(course.CourseID)) { return Conflict(); } else { throw; } } return CreatedAtAction("GetCourse", new { id = course.CourseID }, course); } // DELETE: api/Courses/5 [HttpDelete("{id}")] public async Task<ActionResult<Course>> DeleteCourse(int id) { var course = await _context.Courses.FindAsync(id); if (course == null) { return NotFound(); } _context.Courses.Remove(course); await _context.SaveChangesAsync(); return course; } private bool CourseExists(int id) { return _context.Courses.Any(e => e.CourseID == id); } } }
2.5 运行项目,使用Postman测试接口