Open Project
Open the ASP.NET Core application in Visual Studio 2019.
Add an API controller
Right-click the item and add a new folder named Api.Then, right-click the folder and select Add > New Scaffolded Item.Use the Entity Framework to select the API Controller with actions.Now select an existing model class and click Add.
View generated controllers
The generated code includes a new controller class.At the top of the class definition are two attributes.
[Route("api/[controller]")] [ApiController]public class GamesController : ControllerBase
The first route specifying actions in this controller is api/[controller], which means that if the controller name is GamesController, the route is api/Games.
The second property [ApiController] adds some useful validation to the class, such as ensuring that each action method contains its own [Route] property.
public class GamesController : ControllerBase{ private readonly AppDbContext _context; public GamesController(AppDbContext context) { _context = context; }
The controller uses an existing AppDbContext and passes it to its constructor.Each operation will use this field to process the application's data.
// GET: api/Games[HttpGet]public IEnumerable<Game> GetGame(){ return _context.Game; }
The first method is to use a simple GET request specified by the [HttpGet] property.It takes no parameters and returns a list of all the Games in the database.
// GET: api/Games/5[HttpGet("{id}")]public async Task<IActionResult> GetGame([FromRoute] int id){ if (!ModelState.IsValid) { return BadRequest(ModelState); } var game = await _context.Game.FindAsync(id); if (game == null) { return NotFound(); } return Ok(game); }
The next method specifies the {id} in the route, which will be added to/after the route, so the complete route will be similar to api/Games/5, as shown in the note at the top.The ID input is mapped to the ID parameter on the method.Inside the method, if the model is invalid, a BadRequest result is returned. Download VS 2019 Otherwise, EF will try to find a record that matches the provided id.If not found, the NotFound result will be returned, otherwise the corresponding game record will be returned.
// PUT: api/Games/5 [HttpPut("{id}")] public async Task<IActionResult> PutGame([FromRoute] int id, [FromBody] Game game) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != game.Id) { return BadRequest(); } _context.Entry(game).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GameExists(id)) { return NotFound(); } else { throw; } } return NoContent(); }
Next, use [HttpPut] requests to the API to perform the update.A new Game record is provided in the body of the request.Perform some validation and error checks, and if everything goes well, the records in the database will be updated with the values provided in the body of the request.Otherwise, an appropriate error response will be returned.
// POST: api/Games [HttpPost] public async Task<IActionResult> PostGame([FromBody] Game game) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.Game.Add(game); await _context.SaveChangesAsync(); return CreatedAtAction("GetGame", new { id = game.Id }, game); }
A [HttpPost] request is used to add a new record to the system.As with [HttpPut], the record is added to the body of the request.If valid, EF Core adds the record to the database, and the operation returns the updated record with the database-generated ID and a link to the API record.
// DELETE: api/Games/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteGame([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var game = await _context.Game.FindAsync(id); if (game == null) { return NotFound(); } _context.Game.Remove(game); await _context.SaveChangesAsync(); return Ok(game); }
Finally, [HttpDelete] uses an ID-routed route to delete records.If the request is valid and a record with the given ID exists, EF Core deletes it from the database.
Add Swagger
Swagger is an API documentation and testing tool that can be added to ASP.NET Core applications as a set of services and middleware.To do this, right-click the project and select Manage NuGet Packages.Click Browse, search for Swashbuckle.AspNetCore, and install the appropriate package.
After installation, open Startup.cs and add the following to the end of the ConfigureServices method:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); });
You also need to add Swashbuckle.AspNetCore.Swagger to the top of the file.
Next, before UseMvc, add the following to the Configure method:
// Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
Now you should be able to build and run applications.
In your browser, navigate to the / swagger address bar and you should see a list of API endpoints and models for your application.
Click on an endpoint under Games and try to execute it to see the behavior of different endpoints.