dotnet-webapi
Guides creation and modification of ASP.NET Core Web API endpoints with correct HTTP semantics, OpenAPI metadata, and error handling. USE FOR: adding new API endpoints (controllers or minimal APIs), wiring up OpenAPI/Swagger, creating .http test files, setting up global error handling middleware.
Install / Use
npx skills add dotnet/skills --skill dotnet-webapiInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
Development & EngineeringSupported Platforms
Our assessment of dotnet-webapi
dotnet-webapi scores 87/100 on our quality scale, 846th of 2,398 Development & Engineering skills we index (top 36%).
Its SKILL.md is 21 KB long, well organised into 20 sections with 14 code examples: a thorough specification that gives an agent plenty to work with.
With 5,471 GitHub stars, it is one of the more widely adopted skills in the catalogue.
Maintenance, license and trust
- The repository was last updated 2 days ago, so dotnet-webapi is actively maintained.
- It is released under the MIT license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
dotnet-webapi compared with similar skills
All 4 of these similar skills score higher than dotnet-webapi; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| dotnet-webapi (this skill)by dotnet | 87 | 5.5k | 2d ago | SKILL.md |
| Agent-Reachby Panniantong | 100 | 85.6k | 11d ago | CLAUDE.md |
| headroomby headroomlabs-ai | 100 | 73.9k | today | CLAUDE.md |
| ai-job-searchby MadsLorentzen | 100 | 44.0k | 5d ago | CLAUDE.md |
| claude-howtoby luongnv89 | 100 | 41.7k | today | CLAUDE.md |
Frequently asked questions
- How do I install dotnet-webapi?
- Run
npx skills add dotnet/skills --skill dotnet-webapi. The install tabs above show the steps for each supported agent. - Which AI agents does dotnet-webapi work with?
- It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is dotnet-webapi safe to use?
- It is MIT-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is dotnet-webapi still maintained?
- The repository was last updated 2 days ago, so dotnet-webapi is actively maintained.
Skill content
View source on GitHubname: dotnet-webapi description: > Guides creation and modification of ASP.NET Core Web API endpoints with correct HTTP semantics, OpenAPI metadata, and error handling. USE FOR: adding new API endpoints (controllers or minimal APIs), wiring up OpenAPI/Swagger, creating .http test files, setting up global error handling middleware. DO NOT USE FOR: general C# coding style, EF Core data access or query optimization (use optimizing-ef-core-queries), frontend/Blazor work, gRPC services, or SignalR hubs. license: MIT
ASP.NET Core Web API
Produce well-structured ASP.NET Core Web API endpoints with proper HTTP semantics, OpenAPI documentation, and error handling.
When to Use
Use this skill when working on ASP.NET Core HTTP APIs, including:
- adding or modifying Web API endpoints implemented with controllers or minimal APIs;
- wiring up OpenAPI/Swagger metadata and endpoint documentation;
- defining request/response DTOs and consistent HTTP status code behavior;
- adding
.httpfiles or similar request-based API testing artifacts; - configuring centralized API error handling middleware or exception mapping.
When Not to Use
Do not use this skill for:
- general C# coding style or non-API refactoring;
- EF Core data modeling or query optimization work; use
optimizing-ef-core-queries; - frontend, Razor, or Blazor UI changes;
- gRPC services;
- SignalR hubs or real-time messaging flows.
Inputs / prerequisites
Before applying this skill, gather the project context needed to match the existing API style and wiring:
- the ASP.NET Core entry point, typically
Program.cs; - any existing controllers, especially classes inheriting
ControllerBaseor using[ApiController]; - any existing minimal API registrations such as
app.MapGet,app.MapPost,app.MapPut, orapp.MapDelete; - related DTO, model, validation, and error-handling types already used by the project;
- available build, run, and test commands so changes can be verified.
If the user asks for a new endpoint, inspect the current project structure first so the implementation follows the established conventions rather than mixing styles.
Workflow
Step 1: Determine the API style
Scan the project for existing endpoint patterns before writing any code.
- Search for classes inheriting
ControllerBaseor decorated with[ApiController]. - Search
Program.csor endpoint files forapp.MapGet,app.MapPost, etc. - If the project already uses controllers, continue with controllers.
- If the project already uses minimal APIs, continue with minimal APIs.
- If neither exists (new project), default to minimal APIs unless the user explicitly requests controllers.
Do not mix styles in the same project.
Step 2: Define request and response types
Create dedicated types for API input and output. Never expose EF Core entities directly in request or response bodies.
Use sealed record for all DTOs. Records enforce immutability, provide
value-based equality, and produce concise code. Seal them to prevent unintended
inheritance and enable JIT devirtualization (CA1852).
Naming convention:
| Role | Convention | Example |
|------|-----------|---------|
| Input (create) | Create{Entity}Request | CreateProductRequest |
| Input (update) | Update{Entity}Request | UpdateProductRequest |
| Output (single) | {Entity}Response | ProductResponse |
| Output (list) | {Entity}ListResponse | ProductListResponse |
XML doc comments on all DTOs: Add <summary> XML doc comments to every
request and response type exposed in the API. These comments are automatically
included in the generated OpenAPI specification, producing richer documentation
without extra metadata calls.
Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/openapi-comments
Date and time values — use DateTimeOffset: When a DTO includes a date or
time property, always use DateTimeOffset instead of DateTime.
DateTimeOffset preserves the UTC offset, avoids ambiguous timezone
conversions, and serializes to ISO 8601 with offset information in JSON — which
is what API consumers expect.
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset JSON serialization options — preserve existing behavior by default: For existing APIs, do not introduce stricter serialization/deserialization settings unless the project already uses them or the user explicitly asks for them. Settings such as case-sensitive property matching and strict number handling can break existing clients. For new projects, or when strict JSON handling is explicitly requested, configure options like the following to minimize the potential of processing malicious requests:
// Apply these settings only for new projects, when the existing project already
// uses them, or when the user explicitly requests stricter JSON behavior.
builder.Services.ConfigureHttpJsonOptions(options =>
{
// disallow reading numbers from JSON strings
options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;
// match properties with exact casing during deserialization
options.SerializerOptions.PropertyNameCaseInsensitive = false;
// reject duplicate JSON property names during deserialization
options.SerializerOptions.AllowDuplicateProperties = false;
// omit null properties from serialized output
options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
Enum properties — serialize as strings by default: Unless the user
explicitly requests integer serialization, all enum properties should be
serialized as strings. String-serialized enums are human-readable, less fragile
when values are reordered, and produce better OpenAPI documentation. See Step 4
for the JsonStringEnumConverter configuration.
Response DTOs — use positional sealed records for concise, immutable output:
/// <summary>Represents a product returned by the API.</summary>
public sealed record ProductResponse(
int Id,
string Name,
decimal Price,
Category Category,
bool IsAvailable,
DateTimeOffset CreatedAt);
Request DTOs — use sealed records with init properties so data annotations
work naturally:
/// <summary>Payload for creating a new product.</summary>
public sealed record CreateProductRequest
{
[Required, MaxLength(200)]
public required string Name { get; init; }
[Range(0.01, 999999.99)]
public required decimal Price { get; init; }
public required Category Category { get; init; }
}
Follow the same pattern for Update{Entity}Request records, adding any
additional properties the update requires (e.g., IsAvailable).
Minimal API validation — register explicitly: Data-annotation validation
([Required], [MaxLength], [Range], etc.) is automatic in MVC controllers,
but minimal APIs require explicit opt-in. For .NET 10+ projects using minimal
APIs, add the validation services in Program.cs:
builder.Services.AddValidation();
This wires up an endpoint filter that validates parameters decorated with data
annotations before the handler executes, returning a 400 Bad Request with a
validation problem details response on failure.
Reference: https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-10.0
Do not use mutable classes ({ get; set; }) for DTOs. Mutable DTOs allow
accidental modification after construction and lose the self-documenting
immutability that records provide.
Step 3: Implement the endpoints
Whether using controllers or minimal APIs, follow these HTTP conventions consistently.
Organizing minimal API endpoints: For projects using minimal APIs, organize
endpoints by resource using static classes with a static Map<Resource> method.
This pattern keeps endpoint definitions grouped by resource type, making the
code more maintainable and easier to navigate as the API grows.
Pattern structure:
- Create one static class per resource (e.g.,
ProductEndpoints,CategoryEndpoints). - Define a static
Map<Resource>(this WebApplication app)extension method. - Inside the method, call
MapGet,MapPost,MapPut,MapDelete, etc. for that resource's endpoints. - In
Program.cs, call each resource'sMapmethod in order.
Minimal API return types — prefer TypedResults:
Always prefer TypedResults over the Results factory. TypedResults embeds
response type information in the method signature, giving the OpenAPI generator
richer metadata automatically.
When a handler returns multiple result types (e.g., Ok or NotFound),
annotate the lambda with an explicit Results<T1, T2> return type. This
lets you use TypedResults while still giving the compiler a common type:
async Task<Results<Ok<ProductResponse>, NotFound>> (int id, ...) => ...
Do not use TypedResults.Ok(x) and TypedResults.NotFound() in a bare
ternary without an explicit return type annotation. Ok<T> and NotFound are
different types with no common base the compiler can infer, which causes
CS1593: Delegate 'RequestDelegate' does not take N arguments because the
compiler falls back to matching RequestDelegate(HttpContext).
Fallback — Results factory: If a handler has many conditional branches
(7+ result types), you may use the Results factory (Results.Ok(),
Results.NotFound()) which returns IResult, sacrificing compile-time OpenAPI
inference for simpler signatures.
Status codes:
| Operation | Success | Common errors |
|-----------|---------|---------------|
| GET (single) | 200 OK | 404 Not Found |
| GET (list) | 200 OK | — |
| POST (create) | 201 Created with Location header | 400 Bad Request, 409 Conflict |
| PUT (full update) | 200 OK | 400 Bad Request, 404 Not Found |
| PATCH (partial/action) | 200 OK | 400 Bad Request, 404 Not Found |
| DELETE | 204 No Content | 404 Not Found, 409 Conflict |
POST 201 responses: Always return a Location header pointing to the
newly created resource.
- Controllers: use
CreatedAtAction(nameof(GetById), new { id = ... }, response) - Minimal APIs: use
TypedResults.Created($"/api/products/{id}", response)
CancellationToken: Accept CancellationToken in every endpoint signature
and forward it through to all async calls (service methods, EF Core queries,
HttpClient calls). This allows the server to stop work when a client
disconnects.
// Controller example
[HttpGet("{id}")]
public async Task<ActionResult<ProductResponse>> GetById(
int id, CancellationToken cancellationToken)
{
var product = await _productService.GetByIdAsync(id, cancellationToken);
return product is null ? NotFound() : Ok(product);
}
// Minimal API example — TypedResults with explicit return type (recommended)
app.MapGet("/api/products/{id}", async Task<Results<Ok<ProductResponse>, NotFound>> (
int id, IProductService service, CancellationToken cancellationToken) =>
{
var product = await service.GetByIdAsync(id, cancellationToken);
return product is null ? TypedResults.NotFound() : TypedResults.Ok(product);
});
Step 4: Wire up OpenAPI
Every ASP.NET Core Web API should have OpenAPI documentation. Check whether the project already has OpenAPI configured before adding it.
For .NET 9+ projects, use the built-in ASP.NET Core OpenAPI support
(builder.Services.AddOpenApi() + app.MapOpenApi() in development).
This is all that is needed — no additional packages required.
Do NOT add any Swashbuckle.* NuGet package (Swashbuckle.AspNetCore,
Swashbuckle.AspNetCore.SwaggerUI, Swashbuckle.AspNetCore.SwaggerGen,
etc.) to .NET 9+ projects. Swashbuckle has known compatibility issues with
.NET 9+ and .NET 10 OpenAPI types. For projects targeting .NET 8 or earlier,
Swashbuckle is acceptable. If the project already
Truncated for display — read the full file on GitHub.
Related Skills
Agent-Reach
85.6kGive your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.
headroom
73.9kCompress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
ai-job-search
44.0kThe job search that runs on your machine. AI job application framework built on Claude Code: evaluate postings, tailor CVs, write cover letters, prep interviews. Fork it and own it.
claude-howto
41.7kA visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
