Перейти к содержанию
Skillpedia
API и серверы (бэкенд)5.8k · #14560

dotnet-webapi

Что он делает

Этот скилл направляет создание и изменение конечных точек ASP.NET Core Web API, с контроллерами или минимальными API. Он нужен разработчикам .NET, которые создают HTTP-API и хотят получать аккуратные ответы и документированные конечные точки.

Когда использовать

  • ✓Когда нужно добавить или изменить конечную точку Web API в проекте ASP.NET Core.
  • ✓Когда вам нужна документация OpenAPI или Swagger для API.
  • ✓Когда нужен глобальный обработчик ошибок, который возвращает одинаковые ответы об ошибках.

Ссылка на скилл

https://github.com/dotnet/skills/blob/main/plugins/dotnet-aspnetcore/skills/dotnet-webapi/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/dotnet/skills/blob/main/plugins/dotnet-aspnetcore/skills/dotnet-webapi/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Добавь конечную точку Web API, которая создаёт заказ, возвращает правильный код состояния и описана в OpenAPI.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Агент подстраивается под существующий стиль API в проекте, пишет конечную точку с правильными кодами состояния HTTP и объектами передачи данных, добавляет метаданные OpenAPI и настраивает централизованную обработку ошибок.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

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 .http files 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 ControllerBase or using [ApiController];
  • any existing minimal API registrations such as app.MapGet, app.MapPost, app.MapPut, or app.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.

  1. Search for classes inheriting ControllerBase or decorated with [ApiController].
  2. Search Program.cs or endpoint files for app.MapGet, app.MapPost, etc.
  3. If the project already uses controllers, continue with controllers.
  4. If the project already uses minimal APIs, continue with minimal APIs.
  5. 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 fro
Частые вопросы

Он охватывает запросы к базе данных?

Нет, доступ к данным через Entity Framework относится к отдельному скиллу.

Он может создать файлы тестовых запросов?

Да, он может добавить файлы .http для проверки конечных точек.

Он работает с gRPC или SignalR?

Нет, эти технологии находятся за пределами его области.

Подробности

Оригинальное описание автора

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.

repo: dotnet/skills

Популярность

Звёзды на GitHub
5.8k
Место в рейтинге
#14560
Лицензия
MIT
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы