create-controller
Create API Controller
Create a controller for a given entity in an ASP.NET Core Web API project.
Pre-requisites
- Use Controller-based APIs
- Use System.Text.Json for all JSON data
- The project uses Entity Framework Core 9 — do not install additional packages, the project is already set up.
Steps
-
Create an empty controller with the naming rule:
{EntityName}Controller -
Set up DI and inject Entity Framework context and
ILogger<T>. -
Do not use Entity Class for model binding. Create DTO classes for each CRUD operation instead.
-
Add CRUD REST API methods with required OpenAPI-related annotations.
-
Add
OperationIdto each action method. Example:// Before [HttpGet] // After [HttpGet(Name = "GetCourses")]Give each
OperationIda meaningful name. -
Apply
[ProducesResponseType]attribute to each action reflecting API behavior. -
Edit
coursemanagement.httpfor testing:- Do not touch the existing
@HostAddressvariable definition. - Use the
HostAddressvariable. - Reference related Entity Class for test payloads.
- When writing POST method, don't add Primary Key from the entity.
- Do not touch the existing
-
Run
dotnet buildto verify everything compiles. -
Add
Swashbuckle.AspNetCore.SwaggerUIpackage:dotnet add package Swashbuckle.AspNetCore.SwaggerUI -
Add the following code to
Program.cs:app.UseSwaggerUI(options => { options.SwaggerEndpoint("/openapi/v1.json", "OpenAPI V1"); }); -
Run
dotnet runto verify the application starts successfully.