1. Install VS 2019, SQL Server 2019 (Optional)
2. Open VS and select new ASP.NET Core Web Application project
3. Fill in project name, solution name, modify storage path, etc.
4. Select the version of. NET Core. By default, we select 3.1 and API.
This is the default directory structure after creation
5.Core 3.1 comes with an api called weatherforecast. After creation, we can run it directly to see the effect, as follows:
6. Use nuget to add Entity framework core. Tools --> NuGet Manager Packager-->Manage NuGet Packages for Solution.
Browse -- > Search microsoft. Entityframeworkcore. Sqlserver -- > check the item -- > install
Browse -- > Search microsoft. Entityframeworkcore. Tools -- > check the item -- > install
After the installation is successful, you can view it in the dependencies of the project
7. Use the scaffold dbcontext command in NuGet Packager Console to create the database context.
After success, Model and DB context will be generated in the Models folder
Open the DB context file. There is a warning in it. You will be prompted to move the database connection string out of DB context. Let's put the connection string in the setup.cs file.
8. Create Controller
Auto create
Right click the Controller, select Add, and select new scaffold item
Select API Controller Wtih actions, using Entity Framework
Select Model and DB context
A CS file of UsersController will be generated in the Controller folder. There is a CRUD operation method for Table Users.
Run the project to see the results. Since then, the simple API has been created.
Manually create
Right click Controller, add > Controller > empty Controller
Fill in Controller name, which must be the same as the name of Entity.
Write the code as follows:
The operation results are as follows:
9. postman
https://localhost:44317/api/TODOITEM/3 3--FromRout
Parms --FromQuery
Headers --FromHeader
Body -- FromBody
If you want to transfer JSON formatted data (objects) to the API, add a request Header in the Header: "content type" is "application/json"
In "Body", select "raw" and enter the json format parameter manually.
The results are as follows:
10. Up to now, the API abstraction model we have completed can be referred to as follows.
Next we will complete Repository Patten. As for the benefits of Ropository Patten, after all, it encapsulates one more layer, which plays a role of data isolation to some extent. For the Controller, it is processing logic and should not directly manipulate the data. At the same time, it also provides a possibility for the implementation of data casting.
11. Repository Patten
12. Create a folder called DataRepository.
Create an IUsersRepository interface in the folder.
Create UsersRepository to implement the interface created above.
Modify the code, mainly to migrate the code in the Controller.
UerRepository.cs:
public class UsersRepository : IUsersRepository { private NPT_DataHub_DEVContext _context; public UsersRepository(NPT_DataHub_DEVContext context) { _context = context; } public async Task<User> Add(User user) { await _context.User.AddAsync(user); await _context.SaveChangesAsync(); return user; } public bool Exist(int UserId) { return _context.User.Any(user => user.UserId == UserId); } public async Task<User> Find(int UserId) { return await _context.User.FindAsync(UserId); } public IEnumerable<User> GetAll() { return _context.User; } public async Task<User> Remove(int UserId) { var user = await _context.User.FindAsync(UserId); _context.User.Remove(user); await _context.SaveChangesAsync(); return user; } public async Task<User> Update(User user) { _context.User.Update(user); await _context.SaveChangesAsync(); return user; } }
UsersController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using NPT_API_Test.Models; using NPT_API_Test.DataRepository; namespace NPT_API_Test.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly IUsersRepository _userRepository; public UsersController( IUsersRepository usersRepository) { _userRepository = usersRepository; } // GET: api/Users [HttpGet] public ActionResult<IEnumerable<User>> GetUser() { return new ObjectResult(_userRepository.GetAll()); } // GET: api/Users/5 [HttpGet("{id}")] public async Task<ActionResult<User>> GetUser(int id) { var user = await _userRepository.Find(id); if (user == null) { return NotFound(); } return user; } // PUT: api/Users/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPut("{id}")] public async Task<IActionResult> PutUser(int id, User user) { if (id != user.UserId) { return BadRequest(); } try { await _userRepository.Update(user); } catch (DbUpdateConcurrencyException) { if (! UserExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Users // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPost] public async Task<ActionResult<User>> PostUser(User user) { await _userRepository.Add(user); return CreatedAtAction("GetUser", new { id = user.UserId }, user); } // DELETE: api/Users/5 [HttpDelete("{id}")] public async Task<ActionResult<User>> DeleteUser(int id) { await _userRepository.Remove(id); return Ok(); } private bool UserExists(int id) { return _userRepository.Exist(id); } } }
Test results: