惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Application and Cybersecurity Blog
Application and Cybersecurity Blog
A
About on SuperTechFans
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Help Net Security
Help Net Security
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
O
OpenAI News
美团技术团队
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
Webroot Blog
Webroot Blog
Cyberwarzone
Cyberwarzone
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
T
Tenable Blog
S
Security Affairs
博客园_首页
S
Schneier on Security
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
Spread Privacy
Spread Privacy
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
Kaspersky official blog
Hugging Face - Blog
Hugging Face - Blog
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
Vercel News
Vercel News
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
B
Blog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
Attack and Defense Labs
Attack and Defense Labs
L
LINUX DO - 最新话题
D
DataBreaches.Net
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - Franky
W
WeLiveSecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Check Point Blog
H
Hacker News: Front Page

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
CLAUDE.md for C# and .NET: 13 Rules That Make AI Write Modern, Idiomatic Production Code
Olivia Craft · 2026-05-09 · via DEV Community

Ask Claude Code to "add an endpoint that returns paged orders for a customer" and the output compiles. It also ignores nullable warnings, hides an async void, blocks the thread pool with .Result, wraps everything in try/catch (Exception), reaches for a static DbContext, and sprinkles IConfiguration["..."] strings like glitter. It runs fine on your laptop. It deadlocks in staging.

C# in 2026 is not the C# the model was trained on. NRTs, records, pattern matching, minimal APIs, file-scoped namespaces, and IAsyncEnumerable are table stakes. Half the model's training is .NET Framework era; half the rest is "Hello World" tutorials. A CLAUDE.md next to your .csproj is the cheapest way to drag it forward.

Get the full CLAUDE.md Rules Pack — oliviacraftlat.gumroad.com/l/skdgt. The 13 rules below are a free preview.

1. Nullable reference types on, warnings as errors

<Nullable>enable</Nullable> and <TreatWarningsAsErrors>true</TreatWarningsAsErrors> go in every .csproj for new code. Without NRTs, the model emits string parameters that secretly mean "string or null", forces you to add ?. everywhere downstream, and quietly swallows NullReferenceException at runtime.

<PropertyGroup>
  <Nullable>enable</Nullable>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  <LangVersion>latest</LangVersion>
</PropertyGroup>

Enter fullscreen mode Exit fullscreen mode

Annotate intent: Customer? means may be null; Customer means it never is. Don't chase warnings with ! — the null-forgiving operator is a paper-over.

2. Records for DTOs, events, and value-equal types

When the type is "data, plus equality, plus immutability", reach for record (or record struct). AI defaults to mutable classes with hand-rolled Equals/GetHashCode that drift the moment a property is added.

public sealed record OrderDto(
    Guid Id,
    Guid CustomerId,
    decimal Total,
    IReadOnlyList<OrderLine> Lines);

Enter fullscreen mode Exit fullscreen mode

with-expressions handle the "modify one field" case without mutation. Use class for entities with identity and behavior (EF Core aggregates); use record for transport, requests, responses, and domain events.

3. Switch expressions over if/else chains

Pattern matching is the C# 8+ killer feature, and the model still writes if (x is Foo f && f.Bar > 0) ladders. Switch expressions are exhaustive (the analyzer flags missing cases), shorter, and read top-to-bottom.

public decimal CalculateFee(Payment p) => p switch
{
    { Method: PaymentMethod.Card, Amount: > 1000m } => p.Amount * 0.015m,
    { Method: PaymentMethod.Card }                  => p.Amount * 0.025m,
    { Method: PaymentMethod.BankTransfer }          => 0m,
    _ => throw new ArgumentOutOfRangeException(nameof(p))
};

Enter fullscreen mode Exit fullscreen mode

Property patterns, list patterns, and is not null over != null — they read as English and the analyzer reasons about them.

4. async/await only — no .Result, no .Wait(), no async void

Task.Result and Task.Wait() deadlock under any sync context (ASP.NET legacy, WPF, WinForms) and starve the thread pool elsewhere. async void swallows exceptions and crashes the process. AI reaches for them whenever a sync interface needs to call async code; the fix is to make the interface async, not to block.

public async Task<Order> GetOrderAsync(Guid id, CancellationToken ct)
{
    var order = await _db.Orders
        .Include(o => o.Lines)
        .FirstOrDefaultAsync(o => o.Id == id, ct);

    return order ?? throw new OrderNotFoundException(id);
}

Enter fullscreen mode Exit fullscreen mode

async void is reserved for event handlers. ConfigureAwait(false) in shared libraries; skip it in ASP.NET Core (no sync context to capture).

5. CancellationToken everywhere — propagate, don't drop

Every async method that does I/O takes a CancellationToken and passes it down. Minimal API handlers and controllers get one for free. AI omits the token and turns client disconnects into 30-second hangs.

app.MapGet("/orders/{id:guid}", async (
    Guid id,
    IOrderService svc,
    CancellationToken ct) =>
{
    var order = await svc.GetOrderAsync(id, ct);
    return Results.Ok(order);
});

Enter fullscreen mode Exit fullscreen mode

Name it ct or cancellationToken, never with a default that callers ignore. EF Core, HttpClient, Stream all accept tokens — use them.

6. LINQ for transformation — but no double enumeration

LINQ is idiomatic, but IEnumerable<T> from LINQ is deferred: enumerating twice runs the source twice. Materialize with .ToList() / .ToArray() once when crossing a layer boundary. AI defaults to repeated .Count() and .Any() against the same query — on EF Core that's N extra round-trips.

var unpaid = await db.Orders
    .AsNoTracking()
    .Where(o => o.Status == OrderStatus.Pending)
    .OrderBy(o => o.CreatedAt)
    .Select(o => new OrderDto(o.Id, o.CustomerId, o.Total, o.Lines))
    .ToListAsync(ct);

if (unpaid.Count == 0) return Results.NoContent();
return Results.Ok(unpaid);

Enter fullscreen mode Exit fullscreen mode

EF Core: AsNoTracking() for reads, Include deliberately, project to DTOs with Select instead of fetching whole entities. Never call .ToList() mid-query and then keep filtering — that materialises the world.

7. Dependency injection via constructor — no Service.Instance, no static state

Every collaborator is injected through the constructor. No HttpClient.SharedInstance, no static readonly DbContext, no ServiceLocator.Get<T>(). AI loves singletons because tests are out of scope; you live with them when those services need to be replaced for tests, integration runs, or per-tenant overrides.

public sealed class OrderService(
    AppDbContext db,
    IClock clock,
    ILogger<OrderService> logger) : IOrderService
{
    public async Task<Order> CreateAsync(CreateOrderCommand cmd, CancellationToken ct)
    {
        logger.LogInformation("Creating order for {CustomerId}", cmd.CustomerId);
        // ...
    }
}

Enter fullscreen mode Exit fullscreen mode

Primary constructors keep wiring tight. Lifetimes: Scoped for request-bound work, Singleton for stateless utilities, Transient only when justified.

8. Minimal APIs with typed results — not anonymous-object soup

Minimal APIs (or controllers — pick one per project, don't mix) own routing, model binding, and validation. AI sprinkles Results.Ok(new { ... }) and anonymous types; lock it down with Results<Ok<T>, NotFound> so OpenAPI generation and client codegen actually match what you return.

app.MapGet("/orders/{id:guid}",
    async Task<Results<Ok<OrderDto>, NotFound>> (
        Guid id, IOrderService svc, CancellationToken ct) =>
    {
        var order = await svc.FindAsync(id, ct);
        return order is null
            ? TypedResults.NotFound()
            : TypedResults.Ok(OrderDto.From(order));
    })
.WithName("GetOrder")
.WithOpenApi();

Enter fullscreen mode Exit fullscreen mode

Group endpoints with MapGroup, share auth and validation with IEndpointFilter, and return ValidationProblem for 400s — not by sprinkling ifs inside the handler.

9. Exceptions are specific — no catch (Exception) Pokémon catches

Catch the exception you can handle: DbUpdateConcurrencyException, HttpRequestException, OperationCanceledException. Anything else bubbles to the global handler. AI wraps every block in try/catch (Exception ex) { _logger.LogError(ex, ...); return null; } and you spend Friday debugging silent failures.

try
{
    await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException ex)
{
    logger.LogWarning(ex, "Concurrency conflict on {Id}", id);
    return TypedResults.Conflict();
}

Enter fullscreen mode Exit fullscreen mode

Re-throw with throw; — never throw ex;, which resets the stack trace. OperationCanceledException propagates; don't swallow it, or you'll mask client cancellations as success.

10. Configuration via IOptions<T> — no IConfiguration["Key"] strings

String-keyed configuration scattered across services is untyped, untestable, and validated nowhere. Bind to a typed options class once, register with AddOptions<T>().BindConfiguration(...).ValidateDataAnnotations().ValidateOnStart(), and inject IOptions<T> (or IOptionsSnapshot<T> for reload).

public sealed class StripeOptions
{
    [Required] public string ApiKey { get; init; } = "";
    [Range(1, 60)] public int TimeoutSeconds { get; init; } = 10;
}

builder.Services
    .AddOptions<StripeOptions>()
    .BindConfiguration("Stripe")
    .ValidateDataAnnotations()
    .ValidateOnStart();

Enter fullscreen mode Exit fullscreen mode

Bad config crashes startup, not the first paid request at 2 a.m.

11. Structured logging via ILogger<T> — message templates, not interpolation

logger.LogInformation($"User {userId} did {action}") boxes the values into a single string and destroys structured search. Use the message template form: positional placeholders, named parameters preserved as fields in JSON logs.

logger.LogInformation(
    "Order {OrderId} settled in {ElapsedMs} ms for {CustomerId}",
    order.Id, elapsed.TotalMilliseconds, order.CustomerId);

Enter fullscreen mode Exit fullscreen mode

Levels: Information for business events, Warning for handled anomalies, Error for unhandled failures, Debug for noisy local-only output. No Console.WriteLine in production paths. Use LoggerMessage source generators on hot loops.

12. Tests use xUnit + FluentAssertions — and exercise the public surface

xUnit ([Fact], [Theory]), FluentAssertions for readable failures, and WebApplicationFactory<TProgram> for HTTP-level integration tests. AI writes 200 unit tests against private helpers and zero tests that boot the actual app; flip the ratio.

public class GetOrderTests(OrdersWebAppFactory factory)
    : IClassFixture<OrdersWebAppFactory>
{
    [Fact]
    public async Task Returns_404_when_order_missing()
    {
        var client = factory.CreateClient();
        var resp = await client.GetAsync($"/orders/{Guid.NewGuid()}");
        resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
    }
}

Enter fullscreen mode Exit fullscreen mode

Mock at the seam (IOrderService, IClock), not at DbContext. Use Testcontainers for real Postgres in CI when the schema matters. Snapshot tests for response shapes are fine.

13. Build hygiene: analyzers on, warnings on, formatting enforced

Add Microsoft.CodeAnalysis.NetAnalyzers, enable EnforceCodeStyleInBuild, drop an .editorconfig with the team's rules, and run dotnet format --verify-no-changes in CI. AI will silence analyzers with #pragma warning disable to "ship" — don't let it.

<PropertyGroup>
  <AnalysisMode>AllEnabledByDefault</AnalysisMode>
  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Enter fullscreen mode Exit fullscreen mode

# .editorconfig
[*.cs]
csharp_style_namespace_declarations = file_scoped:error
dotnet_style_qualification_for_field = false:warning
dotnet_diagnostic.CA1062.severity = error  # validate args in public APIs

Enter fullscreen mode Exit fullscreen mode

File-scoped namespaces, ImplicitUsings, and Nullable enabled in every new project template. Suppressing analyzer rules requires a justification comment, reviewed in PR.

A starter CLAUDE.md snippet

# CLAUDE.md — .NET service

## Stack
- C# 13 / .NET 9, NRTs on, warnings as errors, file-scoped namespaces
- ASP.NET Core minimal APIs, EF Core, xUnit + FluentAssertions

## Hard rules
- NRTs enabled; no `!` to silence warnings; warnings = errors.
- Records for DTOs/events/value types; classes for entities and behavior.
- Switch expressions and pattern matching over `if`/`else` chains.
- async/await only. No `.Result`, no `.Wait()`, no `async void` outside event handlers.
- Every async I/O method takes and propagates `CancellationToken`.
- LINQ materialised once at layer boundaries; EF reads use `AsNoTracking`.
- Constructor DI only. No `static` state, no service locator.
- Minimal APIs return `TypedResults`; `MapGroup` + `IEndpointFilter` for shared concerns.
- Catch specific exceptions; rethrow with `throw;`; let `OperationCanceledException` bubble.
- `IOptions<T>` for config with `ValidateDataAnnotations().ValidateOnStart()`.
- Structured logging via `ILogger<T>`; message templates, not interpolation.
- Tests: xUnit, FluentAssertions, `WebApplicationFactory<T>` for HTTP tests.
- Analyzers + `dotnet format --verify-no-changes` in CI.

Enter fullscreen mode Exit fullscreen mode

What Claude gets wrong without these rules

  • Ignores nullability, sprinkles !, ships an NRE on the first edge case.
  • Returns mutable classes with hand-rolled equality that breaks on the next field.
  • Calls .Result inside a sync wrapper and deadlocks the request pipeline.
  • Catches Exception, logs, returns null — silent failure, no signal.
  • Reads config via IConfiguration["Stripe:ApiKey"] in three different services.
  • Writes 200 tests for private helpers and zero tests against the real app.

Drop these 13 rules into CLAUDE.md and the next AI PR looks like a 2026 .NET service, not a 2017 ASP.NET MVC tutorial. Your CI stops failing on warnings and your staging stops deadlocking.

Want this for 20+ stacks with 200+ rules ready to paste? Grab the CLAUDE.md Rules Pack at oliviacraftlat.gumroad.com/l/skdgt.

— Olivia (@OliviaCraftLat)