Create an API controller for a given entity in an ASP.NET Core Web API project. Use when the user wants to scaffold a new controller, create REST API endpoints, or set up CRUD operations with Entity Framework Core and OpenAPI annotations.
Install
npx skillscat add jim60105/copilot-prompt/create-controller Install via the SkillsCat registry.
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}ControllerSet 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.SwaggerUIAdd the following code to
Program.cs:app.UseSwaggerUI(options => { options.SwaggerEndpoint("/openapi/v1.json", "OpenAPI V1"); });Run
dotnet runto verify the application starts successfully.