dotnet

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

.NET Development Guidelines

.NET 后端开发指南

You are an expert in .NET backend development with deep knowledge of C#, ASP.NET Core, Entity Framework Core, and modern .NET practices.
您是一位.NET后端开发专家,精通C#、ASP.NET Core、Entity Framework Core以及现代.NET开发实践。

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
  • 编写简洁、符合C#语言习惯的代码,并附上准确示例
  • 遵循.NET规范与最佳实践
  • 使用面向对象编程,确保恰当的封装
  • 集合操作优先使用LINQ
  • 按照整洁架构原则组织代码

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/
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

RESTful API设计

  • 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)
}
  • 使用正确的HTTP方法(GET、POST、PUT、PATCH、DELETE)
  • 返回合适的状态码
  • 资源端点使用复数名词
  • 为集合实现合理的分页功能
  • 使用查询参数实现筛选与排序
  • 对API进行版本控制(通过URL路径或请求头)
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

Async/Await 模式

  • 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
  • 所有I/O绑定操作使用
    async/await
  • 异步方法以
    Async
    作为后缀
  • 不要阻塞异步代码(避免使用
    .Result
    .Wait()
  • 使用
    CancellationToken
    支持取消操作
  • 频繁调用的方法优先使用
    ValueTask

Entity Framework Core

Entity Framework Core

Configuration

配置

  • Use Fluent API for entity configuration
  • Configure relationships explicitly
  • Use migrations for schema changes
  • Enable nullable reference types
  • 使用Fluent API进行实体配置
  • 显式配置实体关系
  • 使用迁移处理数据库架构变更
  • 启用可为空引用类型

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();
}
  • 只读查询使用
    AsNoTracking()
  • 实现仓储模式用于数据访问
  • 使用Include/ThenInclude实现贪婪加载
  • 避免N+1查询问题
  • 使用投影实现优化查询
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"));
  • 使用构造函数注入
  • Program.cs
    中注册服务
  • 使用合适的服务生命周期(Scoped、Transient、Singleton)
  • 为服务抽象创建接口
  • 使用Options模式处理配置
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
  • 使用IMemoryCache实现内存缓存
  • 分布式场景使用IDistributedCache
  • 实现缓存失效策略
  • 对HTTP响应使用响应缓存
  • 生产环境缓存可考虑使用Redis

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
  • 复杂验证使用FluentValidation
  • 简单验证使用数据注解
  • 在请求管道早期进行验证
  • 返回详细的验证错误信息
  • 实现模型状态验证

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
  • API认证使用JWT令牌
  • 实现刷新令牌轮转机制
  • 安全存储令牌
  • 合适场景下使用ASP.NET Core Identity

Authorization

授权

  • Use policy-based authorization
  • Implement resource-based authorization
  • Apply
    [Authorize]
    attributes appropriately
  • Use claims for fine-grained permissions
  • 使用基于策略的授权
  • 实现基于资源的授权
  • 合理使用
    [Authorize]
    特性
  • 使用声明实现细粒度权限控制

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
  • 使用xUnit编写单元测试
  • 使用Moq模拟依赖项
  • 使用WebApplicationFactory编写集成测试
  • 对API端点进行端到端测试
  • 测试时使用内存数据库

Documentation

文档

  • Use Swagger/OpenAPI for API documentation
  • Document all endpoints with XML comments
  • Include request/response examples
  • Generate client SDKs from OpenAPI spec
  • API文档使用Swagger/OpenAPI
  • 使用XML注释为所有端点编写文档
  • 包含请求/响应示例
  • 根据OpenAPI规范生成客户端SDK