csharp-rules

C#/.NET 规则:关于 C#/.NET 的编码规范,涵盖风格、设计模式、安全性与测试。触发条件包括 .cs、.csproj、.sln 文件或 ASP.NET、ASP.NET Core、EF Core、LINQ、NUnit、xUnit、dotnet 相关项目。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "csharp-rules":https://skillpi.com/zh/skills/deepskill-c1194d353f1fb531993c0ad77383619c8955c0e7fca37ee8433b0843135f3cdc。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

C#/.NET 规则:关于 C#/.NET 的编码规范,涵盖风格、设计模式、安全性与测试。触发条件包括 .cs、.csproj、.sln 文件或 ASP.NET、ASP.NET Core、EF Core、LINQ、NUnit、xUnit、dotnet 相关项目。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: csharp-rules
description: "C#/.NET coding rules: style, patterns, security, testing. Triggers: .cs, .csproj, .sln, ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, dotnet."
effort: medium
user-invocable: false
allowed-tools: Read

C#/.NET Rules

These rules come from app/rules/csharp/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in C#/.NET. Apply them when writing or reviewing C#/.NET code.

C# Coding Style

Naming

  • PascalCase: classes, structs, enums, interfaces, methods, properties, events.
  • camelCase: local variables, parameters, private fields.
  • Prefix interfaces with I: IUserRepository, IDisposable.
  • Prefix private fields with _: private readonly ILogger _logger;.
  • UPPER_SNAKE: not conventional in C#. Use PascalCase for constants.

Nullable Reference Types

  • Enable <Nullable>enable</Nullable> in all projects.
  • Use string? only when null is semantically meaningful.
  • Use ! (null-forgiving) operator sparingly -- only when compiler cannot infer.
  • Use ?? (null-coalescing) and ?. (null-conditional) for safe navigation.
  • Use required modifier (C# 11) on properties that must be set at initialization.

Records and Types

  • Use record for immutable value objects and DTOs.
  • Use record struct for small, stack-allocated value types.
  • Use init properties for immutable-after-construction objects.
  • Use with expressions for non-destructive mutation of records.
  • Use primary constructors (C# 12) for concise class definitions.

Pattern Matching

  • Use is pattern for type checks: if (obj is string s).
  • Use switch expressions for exhaustive matching over enums/types.
  • Use property patterns: user is { Age: > 18, Role: "admin" }.
  • Use relational patterns: size is > 0 and < 100.
  • Use list patterns (C# 11): numbers is [1, 2, .., var last].

Async/Await

  • Suffix async methods with Async: GetUserAsync().
  • Return Task<T> or ValueTask<T>, never void (except event handlers).
  • Use await with ConfigureAwait(false) in library code.
  • Use CancellationToken parameters in all async public APIs.
  • Prefer ValueTask<T> when synchronous completion is common.

File Organization

  • One type per file. File name matches type name.
  • Use file-scoped namespaces (C# 10): namespace MyApp.Services;.
  • Order members: fields, constructors, properties, public methods, private methods.
  • Use global using directives in a single GlobalUsings.cs file.

Formatting

  • Use .editorconfig with C# style rules committed to the repository.
  • Use dotnet format for automated formatting.
  • Use Roslyn analyzers for compile-time style enforcement.
  • Max line length: 120 characters.

C# Frameworks

ASP.NET Core

  • Use minimal APIs for simple endpoints. Use controllers for complex APIs.
  • Use [ApiController] attribute for automatic model validation and error responses.
  • Use Results.Ok(), Results.NotFound() for typed HTTP results.
  • Use endpoint filters / middleware for cross-cutting concerns.
  • Use IHostedService / BackgroundService for long-running background tasks.
  • Map routes with app.MapGet(), app.MapPost() for minimal API style.

Entity Framework Core

  • Use code-first migrations: dotnet ef migrations add, dotnet ef database update.
  • Use DbContext with scoped lifetime (one per request).
  • Use AsNoTracking() for read-only queries. Use AsTracking() only for updates.
  • Use Include() / ThenInclude() for eager loading related entities.
  • Use shadow properties for audit fields (CreatedAt, UpdatedAt).
  • Use HasQueryFilter() for soft-delete and multi-tenancy global filters.

Blazor

  • Use Blazor Server for internal tools. Use Blazor WASM for public-facing SPAs.
  • Use @inject for dependency injection in components.
  • Use EventCallback<T> for parent-child component communication.
  • Use CascadingValue for deeply shared state (theme, auth).
  • Use StateContainer pattern with events for cross-component state management.

SignalR

  • Use strongly-typed hubs: Hub<IClientMethods> for compile-time safety.
  • Use HubContext<T> for sending messages from outside hubs.
  • Use groups for targeted broadcasting: Groups.AddToGroupAsync().
  • Configure automatic reconnection on the client side.

MassTransit / Messaging

  • Use MassTransit for message bus abstraction over RabbitMQ/Azure Service Bus.
  • Define messages as record types for immutability.
  • Use consumers (IConsumer<T>) for message handling.
  • Use sagas for long-running, multi-step workflows with state.
  • Use retry and circuit breaker policies for transient failures.

Logging

  • Use ILogger<T> via DI. Never instantiate loggers manually.
  • Use structured logging: _logger.LogInformation("User {UserId} logged in", userId).
  • Use Serilog with sinks for structured, centralized logging.
  • Use log scopes for request correlation: using (_logger.BeginScope(...)).

Configuration

  • Use appsettings.json + environment-specific overrides + environment variables.
  • Bind configuration sections to strongly-typed classes with IOptions<T>.
  • Use IOptionsMonitor<T> for configuration that changes at runtime.
  • Validate configuration at startup with ValidateDataAnnotations().

Health Checks

  • Use app.MapHealthChecks("/health") for liveness probes.
  • Register custom health checks for database, cache, and external service dependencies.
  • Use AspNetCore.HealthChecks.* NuGet packages for common checks.

C# Patterns

Error Handling

  • Use exceptions for truly exceptional conditions. Use Result<T> pattern for expected failures.
  • Create domain exception hierarchies: class DomainException : Exception.
  • Use when clause in catch: catch (HttpRequestException e) when (e.StatusCode == 404).
  • Use ExceptionDispatchInfo.Capture(e).Throw() to preserve original stack trace.
  • Return Result<T, Error> types for operations with expected failure modes.

Async Patterns

  • Use Task.WhenAll() for concurrent independent operations.
  • Use SemaphoreSlim for async-compatible resource limiting.
  • Use Channel<T> for async producer-consumer patterns.
  • Use IAsyncEnumerable<T> for streaming data from async sources.
  • Use Polly for retry, circuit breaker, and timeout policies.
  • Never use .Result or .Wait() on tasks (deadlock risk). Always await.

Dependency Injection

  • Use constructor injection exclusively. Avoid service locator pattern.
  • Register services in Program.cs or IServiceCollection extension methods.
  • Use Scoped for request-lifetime services, Singleton for stateless, Transient for lightweight.
  • Use IOptions<T> pattern for configuration injection.
  • Validate DI registrations at startup with ValidateOnBuild = true.

LINQ

  • Use method syntax for complex queries. Use query syntax for joins.
  • Use FirstOrDefault() over First() for safe access.
  • Use AsNoTracking() for read-only EF Core queries (performance).
  • Avoid materializing large collections: use IQueryable<T> until final projection.
  • Use Select() to project only needed columns from database queries.

Disposable Pattern

  • Implement IAsyncDisposable for async cleanup.
  • Use await using var resource = ...; for deterministic async disposal.
  • Use IDisposable with using declaration (C# 8) for scope-based cleanup.
  • Register disposable services in DI container (auto-disposed at scope end).

Mediator / CQRS

  • Use MediatR for command/query separation and pipeline behaviors.
  • Commands: IRequest<Result> for mutations. Queries: IRequest<T> for reads.
  • Use pipeline behaviors for cross-cutting: validation, logging, transactions.
  • Keep handlers thin: delegate to domain services for business logic.

Value Objects

  • Use record types for value objects with structural equality.
  • Use factory methods with validation: public static Result<Email> Create(string value).
  • Override ToString() for logging-friendly representations.
  • Use implicit/explicit operators sparingly for primitive wrapper conversions.

Anti-Patterns

  • Service locator: inject dependencies, do not resolve from container.
  • async void: use only for event handlers. Everything else returns Task.
  • Nested try-catch: flatten with early returns or guard clauses.
  • Anemic domain model: put behavior in domain objects, not only services.
  • Over-abstracting: do not create interfaces for classes with only one implementation.

C# Security

Input Validation

  • Use data annotations ([Required], [StringLength], [Range]) on request models.
  • Use [ApiController] for automatic 400 responses on validation failure.
  • Use FluentValidation for complex, rule-based validation logic.
  • Never trust client-provided IDs. Verify resource ownership server-side.
  • Sanitize HTML input with a library like HtmlSanitizer. Never render raw user HTML.

SQL Injection

  • Use EF Core parameterized queries exclusively. Never concatenate SQL.
  • Use FromSqlInterpolated() over FromSqlRaw() for raw SQL (auto-parameterized).
  • Use stored procedures via context.Database.ExecuteSqlInterpolatedAsync().
  • Audit all FromSqlRaw() calls for parameter interpolation risks.
  • Use Dapper with parameterized queries: @param syntax in SQL strings.

Authentication

  • Use ASP.NET Core Identity for user management and password hashing.
  • Use AddAuthentication().AddJwtBearer() for JWT-based API auth.
  • Use short-lived access tokens (15 min) with refresh token rotation.
  • Use [Authorize] attribute globally. Use [AllowAnonymous] selectively.
  • Use HTTPS redirection: app.UseHttpsRedirection().

Authorization

  • Use policy-based authorization: [Authorize(Policy = "AdminOnly")].
  • Use IAuthorizationHandler for custom authorization logic.
  • Use resource-based authorization for object-level access control.
  • Default deny: apply [Authorize] at controller/app level, opt out per endpoint.
  • Check ownership in service layer, not just role membership.

CSRF and XSS

  • Use anti-forgery tokens for form-based submissions.
  • Razor/Blazor auto-encodes output. Never use @Html.Raw() with user data.
  • Set Content-Security-Policy headers to restrict script sources.
  • Use SameSite=Strict on cookies for CSRF mitigation.
  • Enable CORS only for specific origins. Never use AllowAnyOrigin() with credentials.

Data Protection

  • Use IDataProtectionProvider for symmetric encryption of sensitive data.
  • Use SecureString or ProtectedData for in-memory sensitive data (limited use).
  • Use ASP.NET Core Data Protection API for token and cookie encryption.
  • Hash passwords with PasswordHasher<T> (PBKDF2 with salt).

Secrets Management

  • Use dotnet user-secrets for local development. Use Azure Key Vault for production.
  • Use IConfiguration with environment variable providers. Never hardcode secrets.
  • Use [SensitiveData] attributes to exclude fields from logging and serialization.
  • Never log request headers containing Authorization or cookie values.

Dependency Security

  • Run dotnet list package --vulnerable to check for known CVEs.
  • Use Dependabot or NuGetAudit for automated vulnerability scanning.
  • Pin package versions explicitly. Avoid floating version ranges.
  • Update Microsoft.AspNetCore.* packages promptly for security patches.

C# Testing

Framework

  • Use xUnit as the primary test framework (modern, extensible).
  • Use NSubstitute for mocking (clean syntax, no setup boilerplate).
  • Use FluentAssertions for readable, expressive assertions.
  • Use Testcontainers for integration tests with databases and services.

File Naming

  • Test files: FooTests.cs in a separate *.Tests project.
  • Mirror source project namespace structure in test project.
  • Integration tests: separate *.IntegrationTests project.
  • Use [Collection("Database")] for shared fixtures across test classes.

Structure

  • Use [Fact] for single test cases. Use [Theory] for parameterized tests.
  • Use [InlineData] or [MemberData] for test data in theories.
  • Use constructor injection for per-test setup. Use IClassFixture<T> for shared setup.
  • Name tests: MethodName_Scenario_ExpectedResult.

Assertions (FluentAssertions)

  • Use result.Should().Be(expected) for value assertions.
  • Use action.Should().Throw<InvalidOperationException>() for exception testing.
  • Use collection.Should().ContainSingle(x => x.Id == 1) for collection assertions.
  • Use result.Should().BeEquivalentTo(expected) for deep object comparison.
  • Use execution.Should().CompleteWithinAsync(5.Seconds()) for timeout assertions.

Mocking (NSubstitute)

  • Create mocks: var repo = Substitute.For<IUserRepository>().
  • Stub returns: repo.GetAsync(1).Returns(user).
  • Verify calls: repo.Received(1).SaveAsync(Arg.Any<User>()).
  • Use Arg.Is<T>(predicate) for argument matching.
  • Use ReturnsForAnyArgs() for lenient stubs in arrangement-focused tests.

Integration Testing

  • Use WebApplicationFactory<Program> for ASP.NET Core integration tests.
  • Override services with WithWebHostBuilder(b => b.ConfigureServices(...)).
  • Use HttpClient from factory for endpoint testing.
  • Use Respawn for database cleanup between tests.
  • Use [Collection] attribute to prevent parallel execution of shared-resource tests.

Test Data

  • Use Builder pattern for complex test data: new UserBuilder().WithName("Ada").Build().
  • Use AutoFixture for auto-generated test data.
  • Use Bogus library for realistic fake data generation.
  • Keep test data creation close to the test, not in distant shared files.

Best Practices

  • Test behavior, not implementation. Avoid testing private methods.
  • Keep tests independent. No shared mutable state between tests.
  • Use CancellationToken.None explicitly in async test calls.
  • Run tests in CI with dotnet test --blame-hang-timeout 60s.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • C#/.NET 编码规范覆盖全面,包含风格、框架、模式、安全、测试五大核心领域
  • 提供具体可落地的最佳实践,如 nullable 引用类型、async/await 规范、EF Core 优化等
  • 适用于日常开发、代码审查、团队标准化等多种高频刚需场景
触发精准90/100

亮点

  • 触发词覆盖完整,包含 .cs、.csproj、.sln、ASP.NET Core、EF Core、xUnit 等主流技术关键词
  • 边界清晰,不易与其他语言或框架的 Skill 产生误触
结构规范85/100

待提升项

  • 缺少 When to Use 和端到端示例章节 原报告严重程度:轻微

    文档结构良好但缺少显式的使用场景说明和完整示例

    改进建议:建议补充 When to Use 章节说明适用场景,并增加一个端到端的代码示例展示规范应用

亮点

  • 文档结构清晰,分 Style/Frameworks/Patterns/Security/Testing 五大模块组织
  • 每个子项都有具体规则说明,内容详实且层次分明
执行可靠95/100

亮点

  • 内容来自 ai-toolkit 官方规则集,来源可信度高
  • 覆盖主要异常处理、安全实践和测试规范,无执行风险
  • 提供了具体的工具链建议(如 dotnet format、Roslyn analyzers)
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 211 行

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。