dotnet — скилл для Claude Code: правила .NET-бэкенда
Задаёт агенту правила C#, ASP.NET Core и Entity Framework Core: структура проекта, async/await, DI, кэш, тесты.
npx skills add Mindrally/skills --skill dotnet -a claude-codeЧто делает dotnet
Скилл описывает, как писать бэкенд на .NET: идиоматичный C#, Clean Architecture, RESTful-эндпоинты с правильными HTTP-методами и кодами ответа. Агент получает готовую раскладку src/Domain, src/Application, src/Infrastructure, src/WebApi и tests/UnitTests, tests/IntegrationTests — и раскладывает код по ней, а не как придётся.
Внутри — набор правил по слоям. Для async/await: суффикс Async у методов, CancellationToken, никаких .Result и .Wait(). Для EF Core: Fluent API, миграции, AsNoTracking() на чтение, Include/ThenInclude, проекции вместо вытягивания целых сущностей. Плюс DI с конструкторной инъекцией и регистрацией в Program.cs, кэш через IMemoryCache и IDistributedCache, валидация на FluentValidation и Data Annotations, JWT с ротацией refresh-токенов, policy-based авторизация, xUnit с Moq и WebApplicationFactory, Swagger/OpenAPI.
Скилл текстовый: это инструкция для агента, а не генератор кода. Если в проекте уже принят другой стиль — скажем, контроллеры без Clean Architecture или Dapper вместо EF Core — правила начнут спорить с существующей кодовой базой, и это повод либо поправить скилл под себя, либо не ставить его.
Какие задачи решает
- разложить решение на Domain, Application, Infrastructure и WebApi
- переписать синхронные вызовы EF Core на async с CancellationToken
- убрать N+1 запросы через Include и проекции
- настроить JWT-аутентификацию с ротацией refresh-токенов
- добавить интеграционные тесты на WebApplicationFactory
Примеры запросов агенту
- Создай UsersController по правилам скилла dotnet: пагинация, фильтры, версия в пути
- Перепиши этот репозиторий на AsNoTracking и проекции, проверь на N+1
- Настрой регистрацию сервисов и Options pattern в Program.cs
Как установить dotnet
1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill dotnet -a claude-code2Вручную: положить файлы
~/.claude/skills/dotnet/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/dotnet/
1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill dotnet -a codex2Вручную: положить файлы
.agents/skills/dotnet/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill dotnet -a cursor2Вручную: положить файлы
.cursor/skills/dotnet/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install Mindrally/skills dotnet2Вручную: положить файлы
.github/skills/dotnet/SKILL.md1Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill dotnet -a gemini-cli2Командой платформы
gemini skills install https://github.com/Mindrally/skills --path dotnetВручную: положить файлы
.devin/skills/dotnet/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add Mindrally/skills --skill dotnet -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора168
Похожие
Рядом в теме «Бэкенд и API»
Всё по теме «Бэкенд и API» →Вопросы о dotnet
Как установить dotnet в Claude?
Выполните npx skills add Mindrally/skills --skill dotnet -a claude-code. Файл появится по пути ~/.claude/skills/dotnet/SKILL.md.
Что делает скилл dotnet?
Даёт агенту правила .NET-бэкенда: стиль C#, структура решения, async/await, EF Core, DI, кэш, валидация, безопасность и тесты. Агент опирается на них, когда пишет или правит код.
Скилл навязывает Clean Architecture?
Да, структура проекта в нём задана через Domain, Application, Infrastructure и WebApi. Если у вас другая раскладка, правила придётся править под проект.
Исходный текст
SKILL.md · Apache-2.0
---
name: dotnet
description: Guidelines for .NET backend development with C#, ASP.NET Core, and Entity Framework Core
metadata:
maintainer: Mindrally
source: https://github.com/Mindrally/skills
---
# .NET Development Guidelines
You are an expert in .NET backend development with deep knowledge of C#, ASP.NET Core, Entity Framework Core, and modern .NET practices.
## Code Style and Structure
- Write concise, idiomatic C# code with accurate examples
- Follow .NET conventions and best practices
- Use object-oriented programming with proper encapsulation
- Prefer LINQ for collection operations
- Structure code according to Clean Architecture principles
## Project Structure
```
src/
Domain/ # Entities, value objects, domain logic
Application/ # Use cases, DTOs, interfaces
Infrastructure/ # Data access, external services
WebApi/ # Controllers, middleware, configuration
tests/
UnitTests/
IntegrationTests/
```
## RESTful API Design
- Use proper HTTP methods (GET, POST, PUT, PATCH, DELETE)
- Return appropriate status codes
- Use plural nouns for resource endpoints
- Implement proper pagination for collections
- Use query parameters for filtering and sorting
- Version APIs (URL path or header)
```csharp
[ApiController]
[Route("api/v1/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers([FromQuery] PaginationParams pagination)
[HttpGet("{id}")]
public async Task<ActionResult<UserDto>> GetUser(int id)
[HttpPost]
public async Task<ActionResult<UserDto>> CreateUser(CreateUserDto dto)
}
```
## Async/Await Patterns
- Use `async/await` for all I/O-bound operations
- Suffix async methods with `Async`
- Don't block on async code (avoid `.Result` and `.Wait()`)
- Use `CancellationToken` for cancellation support
- Prefer `ValueTask` for frequently-called methods
## Entity Framework Core
### Configuration
- Use Fluent API for entity configuration
- Configure relationships explicitly
- Use migrations for schema changes
- Enable nullable reference types
### Best Practices
- Use `AsNoTracking()` for read-only queries
- Implement the Repository pattern for data access
- Use Include/ThenInclude for eager loading
- Avoid N+1 query problems
- Use projections for optimized queries
```csharp
public async Task<IEnumerable<UserDto>> GetUsersAsync()
{
return await _context.Users
.AsNoTracking()
.Select(u => new UserDto
{
Id = u.Id,
Name = u.Name
})
.ToListAsync();
}
```
## Dependency Injection
- Use constructor injection
- Register services in `Program.cs`
- Use appropriate lifetimes (Scoped, Transient, Singleton)
- Create interfaces for service abstractions
- Use Options pattern for configuration
```csharp
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("Jwt"));
```
## Caching
- Use IMemoryCache for in-memory caching
- Use IDistributedCache for distributed scenarios
- Implement cache invalidation strategies
- Use response caching for HTTP responses
- Consider Redis for production caching
## Validation
- Use FluentValidation for complex validation
- Use Data Annotations for simple validation
- Validate early in the request pipeline
- Return detailed validation errors
- Implement model state validation
## Error Handling
- Use global exception handling middleware
- Create custom exception types
- Return consistent error responses
- Log exceptions with context
- Don't expose internal details
## Security
### Authentication
- Use JWT tokens for API authentication
- Implement refresh token rotation
- Store tokens securely
- Use ASP.NET Core Identity when appropriate
### Authorization
- Use policy-based authorization
- Implement resource-based authorization
- Apply `[Authorize]` attributes appropriately
- Use claims for fine-grained permissions
## Testing
- Write unit tests with xUnit
- Use Moq for mocking dependencies
- Write integration tests with WebApplicationFactory
- Test API endpoints end-to-end
- Use in-memory database for testing
## Documentation
- Use Swagger/OpenAPI for API documentation
- Document all endpoints with XML comments
- Include request/response examples
- Generate client SDKs from OpenAPI spec
© Mindrally · Apache-2.0 · Mindrally/skills