aspnetcore
Host-level .NET code for ASP.NET Core 10 and worker services. Covers the Generic Host, DI lifetimes, options, middleware order, minimal API endpoints, ProblemDetails, typed HTTP clients with resilience, health checks, background services, and the wiring of CORS, rate limits, and authentication. Use when the user writes or reviews Program.cs, endpoints, controllers, middleware, DI registrations, options classes, HttpClient code, BackgroundService or IHostedService, or health checks in a project with Microsoft.NET.Sdk.Web or Microsoft.Extensions.Hosting. Not for C# language rules (dev-stack:csharp), security rules (dev-stack:secure-coding), OpenAPI and versioning detail (dev-stack:aspnetcore-openapi), FluentValidation rules (dev-stack:fluentvalidation), EF Core (dev-stack:efcore), logging setup (dev-stack:dotnet-observability), or Aspire AppHost wiring.
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- aspnetcore
- metadata
- { "verified": "2026-10-27", "versions": ".NET 10 (10.0.14, SDK 10.0.403), ASP.NET Core 10, Microsoft.Extensions.Http.Resilience 10.11.0, .NET 11 RC 3 in references/net11.md" }
- description
- Host-level .NET code for ASP.NET Core 10 and worker services. Covers the Generic Host, DI lifetimes, options, middleware order, minimal API endpoints, ProblemDetails, typed HTTP clients with resilience, health checks, background services, and the wiring of CORS, rate limits, and authentication. Use when the user writes or reviews Program.cs, endpoints, controllers, middleware, DI registrations, options classes, HttpClient code, BackgroundService or IHostedService, or health checks in a project with Microsoft.NET.Sdk.Web or Microsoft.Extensions.Hosting. Not for C# language rules (dev-stack:csharp), security rules (dev-stack:secure-coding), OpenAPI and versioning detail (dev-stack:aspnetcore-openapi), FluentValidation rules (dev-stack:fluentvalidation), EF Core (dev-stack:efcore), logging setup (dev-stack:dotnet-observability), or Aspire AppHost wiring.
02 资源文件 15
- 参考文档references/decisions.md21.7 KB
- 参考文档references/endpoints-errors.md15.3 KB
- 参考文档references/hosting-di-options.md10.3 KB
- 参考文档references/http-resilience.md9.0 KB
- 参考文档references/language.md4.7 KB
- 参考文档references/net11.md7.0 KB
- 参考文档references/pipeline-wiring.md9.1 KB
- 参考文档references/program-template.md18.2 KB
- 参考文档references/review-checklist.md7.4 KB
- 参考文档references/sources.md9.3 KB
- 参考文档references/stack-rules.md7.6 KB
- 参考文档rules.json23.9 KB
- 脚本scripts/convert.py2.9 KB
- 脚本scripts/doccheck.py28.8 KB
- 脚本scripts/stackcheck.py11.9 KB
03 SKILL.md 正文
ASP.NET Core and the Generic Host
This skill covers code that needs a host: IServiceCollection, IHost, HttpContext, or an endpoint. Code that compiles in a plain class library is dev-stack:csharp, and this skill does not repeat its rules. Security rules are in dev-stack:secure-coding. This skill only shows where the security parts go in the pipeline.
First
- Read
references/stack-rules.md. - Read the version gate:
- Read
TargetFrameworkin the*.csprojfiles and inDirectory.Build.props, and theSdkattribute. net10.0: use this file. The app runs on runtime 10.0.14 or later, a security release of 2026-10-25. Check the base image tag or the runtime version in CI.net11.0: also readreferences/net11.md. Its rules apply only when the project targetsnet11.0.net8.0ornet9.0: the rules apply, exceptAddValidation(rule 24) and the .NET 10 behavior changes (rules 9, 22, 34). Both versions end support on 2026-11-10. Tell the human.- A ServiceDefaults project (Aspire) exists: it already adds resilience, health checks, and OpenTelemetry. Do not add them a second time. Use the
aspireskill for that project.
- Read
- Read
Program.csand one existing feature before you write. The project style wins in existing code (stack rule 3).
Done when you can name the target framework, the endpoint style (minimal APIs or controllers), the validation library, and the error style of the project.
Defaults for new code
Existing code keeps its style. For new code, use the accepted decision in docs/dev-team/decisions.md. When a decision has no accepted answer, ask the human (stack rule 4). The detail of each decision is in references/decisions.md.
| Area | Default | ID |
|---|---|---|
| Endpoints | Minimal APIs | API-01 |
| Organization | Static MapX per feature, MapGroup, named static handler methods |
API-02 |
| Contracts | sealed record per request and per response, no entities |
API-03 |
| Errors | ProblemDetails everywhere, extension code, traceId |
API-04 |
| Expected failures | TypedResults union, no result library |
API-05 |
| Handlers | Direct handler class, no mediator (MediatR is not allowed) | API-06 |
| Mapping | Manual, Mapperly for large mappings (AutoMapper is not allowed) | API-07 |
| Validation | AddValidation for shape rules, FluentValidation when the project uses it |
API-08 |
| JSON | Web defaults, JsonStringEnumConverter, NumberHandling.Strict, DateTimeOffset |
API-11 |
| Paging | Offset with a maximum page size and a stable sort | API-12 |
| Idempotency | Natural (client id or unique key), key header only for external side effects | API-13 |
| Rate limiting | Built-in limiter, 429, named policies on sensitive endpoints | API-14 |
| CORS | Same origin, else one named policy with exact origins | API-15 |
| Health | /healthz/live and /healthz/ready |
API-16 |
| URLs | /api/orders/{id}/line-items, actions as POST /api/orders/{id}/cancel |
API-17 |
| Options | Typed options, DataAnnotations, ValidateOnStart |
CFG-01 |
| Secrets | User-secrets in Development, environment or orchestrator secrets in production | CFG-02 |
| Feature flags | Plain options, Microsoft.FeatureManagement for rollouts | CFG-03 |
| Outbound HTTP | Typed client | CFG-05 |
| Resilience | Standard handler on all clients, no retry for unsafe methods | CFG-06 |
| Background work | BackgroundService, Hangfire when a job must survive a restart |
CFG-07 |
| Authentication | JWT bearer from the IdP of the organization, browser SPA through a BFF | CFG-08 |
| Authorization | Fallback policy "authenticated user", named policies | CFG-09 |
| Messages | Stable code plus English detail, the client translates |
CFG-10 |
Rules
Host and DI
- Use
WebApplication.CreateBuilderfor web apps andHost.CreateApplicationBuilderfor workers.WebHostandWebHostBuilderare obsolete in .NET 10. AStartupclass still works, but it is the old model. - Register the services of a feature in
AddX(this IServiceCollection)and map its endpoints inMapX(this IEndpointRouteBuilder).Program.csthen stays short. - Turn on
ValidateScopesandValidateOnBuildin each environment withbuilder.Host.UseDefaultServiceProvider. Production turns them off by default, so a captive dependency shows only under load. - A singleton or a hosted service does not take a scoped service. Create a scope per unit of work with
IServiceScopeFactory.CreateAsyncScope(). - Do not call
BuildServiceProvider()during registration. It makes a second container with its own singletons. Use the(sp, ...) =>factory overloads orIOptions<T>.
Configuration and options
- Bind each settings section to an options class:
AddOptions<T>().BindConfiguration(section).ValidateDataAnnotations().ValidateOnStart(). Bad configuration then stops the start, not the first request. - Mark nested objects with
[ValidateObjectMembers]and lists with[ValidateEnumeratedItems]. Without them, the validator skips the members. For trimming or native AOT, use a source-generated[OptionsValidator]. - Read
IOptions<T>for values that do not change,IOptionsMonitor<T>in a singleton that must see changes. UseIOptionsSnapshot<T>only in scoped services. - .NET 10: a JSON
nullin configuration now binds asnull(ordefault(T)for a value type). It no longer keeps the default value of the class. Remove anullentry that means "use the default", and validate required values. - Keep secrets out of
appsettings.json. Read them from user-secrets in Development and from environment variables, orchestrator secrets, or a vault in production.
Pipeline order
- Add middleware in this order:
UseForwardedHeaders(behind a proxy),UseExceptionHandler,UseStatusCodePages,UseHsts,UseHttpsRedirection,UseCors,UseAuthentication,UseAuthorization,UseRateLimiter, then the endpoints. The order is the behavior: a wrong order gives a wrong client IP, failed CORS preflights, or unprotected endpoints.
Endpoints
- Write new endpoints as minimal APIs. In a project with controllers, add controllers. Do not mix the two styles in one project.
- Return
TypedResults. Declare more than one outcome with aResults<T1, T2>return type. A ternary withTypedResultsand no declared return type does not compile (CS1678, CS1661). - Take a
CancellationTokenin each handler and pass it to each I/O call (CA2016). - A create returns 201 with a
Locationheader (TypedResults.Created,CreatedAtRoute). A delete returns 204. - Use
sealed recordtypes for requests and responses, andDateTimeOffsetfor instants. Do not expose EF entities, because they leak fields and change the contract with each schema change. - Call handler classes directly and map with a static
ToResponse()method or a constructor. MediatR and AutoMapper are not allowed (stack rule 5). - Configure JSON with
ConfigureHttpJsonOptionsfor minimal APIs andAddJsonOptionsfor controllers. They are two different option objects. In an existing API, keep the JSON settings, because a change breaks clients.
Errors
- Register
AddProblemDetails(),UseExceptionHandler(), andUseStatusCodePages(). Then each error isapplication/problem+json, and endpoints need no try/catch. - Return expected failures as results:
TypedResults.NotFound(), orTypedResults.Problemwith status 409 and acodeextension. Throw exceptions only for bugs and infrastructure failures. - Map infrastructure exceptions to a status code in one
IExceptionHandler, or withExceptionHandlerOptions.StatusCodeSelector. - .NET 10: when
TryHandleAsyncreturnstrue, the middleware does not log the exception. It also does not adderror.typeto the metric. Log in the handler, or setSuppressDiagnosticsCallback = _ => false. - Do not put
exception.Messageor a stack trace in a response. Do not callUseDeveloperExceptionPage():WebApplicationturns it on in Development.
Validation
- .NET 10 minimal APIs: call
builder.Services.AddValidation()and put DataAnnotations on the request records. Invalid input then gets a 400 ProblemDetails. The source generator sees only the types of the assembly that callsAddValidation. - When the project uses FluentValidation: inject
IValidator<T>, callValidateAsyncwith the token, and returnTypedResults.ValidationProblem(result.ToDictionary()). For minimal APIs, use one small generic endpoint filter (references/endpoints-errors.md). Do not use the packageFluentValidation.AspNetCore: its owner deprecated it. Rules for validators:dev-stack:fluentvalidation. - Validate one contract with one library. Two libraries give two error formats.
Outbound HTTP
- Use typed clients from
AddHttpClient<TClient>(). Do not createnew HttpClient()per call, because it exhausts sockets. - Do not inject a typed client into a singleton. The singleton keeps one handler and does not see DNS changes. In a singleton, inject
IHttpClientFactoryand create a named client per call. - Add one resilience handler per client:
ConfigureHttpClientDefaults(b => b.AddStandardResilienceHandler()). A second handler on a client stacks, and a test counted 16 attempts, not 4 attempts. To change one client, first callRemoveAllResilienceHandlers()(experimental, EXTEXP0001). Then add the handler of the client. - Turn off retries for calls that are not idempotent:
options.Retry.DisableForUnsafeHttpMethods(). The standard handler retries POST by default and can write twice. - Keep
HttpClient.Timeout(100 s default) above the total timeout of the pipeline (30 s default), or setTimeout.InfiniteTimeSpan. - Do not add
Microsoft.Extensions.Http.Pollyto new code. It pins Polly 7. UseMicrosoft.Extensions.Http.Resilience.
Health, background work, shutdown
- Liveness runs no checks (
Predicate = _ => false). Readiness runs the checks with the tagready. Mark bothAllowAnonymous()andShortCircuit(), and keep them off the public ingress. - .NET 10:
ExecuteAsyncruns fully on a background thread, so code before the firstawaitno longer delays the start. Put work that must finish before the app takes traffic inStartAsync. - In a
BackgroundServiceloop, usePeriodicTimer(period, timeProvider), one scope per iteration, and a catch per iteration that letsOperationCanceledExceptionpass. An unhandled exception stops the host. - Pass
stoppingTokento each call. Keep shutdown work underHostOptions.ShutdownTimeout(30 s default) and under the grace period of the orchestrator. - For work that starts in a request and ends later, write to a
Channel<T>that aBackgroundServicereads.Task.Runfrom a request loses the work on shutdown and loses the request scope.
Cross-cutting wiring
The security rules for these parts are in dev-stack:secure-coding. This skill gives the place in the pipeline.
- Behind a proxy, configure
KnownIPNetworksorKnownProxiesand callUseForwardedHeadersfirst.KnownNetworksis obsolete (ASPDEPR005). - CORS: one named policy with exact origins from configuration. Call
UseCorsbeforeUseAuthorization. - Authorization: set a fallback policy
RequireAuthenticatedUser(), use named policies, and mark public endpointsAllowAnonymous(). A forgotten attribute then fails closed. - Rate limiting:
AddRateLimiterwithRejectionStatusCode = 429(the default is 503), andRequireRateLimitingon login, export, upload, and expensive endpoints. - File uploads: follow
dev-stack:secure-coding(file signatures, size limits, storage).
OpenAPI and versioning
- Use
AddOpenApi()andMapOpenApi()in Development. Do not add Swashbuckle to a new project (API-09). Do not call.WithOpenApi()(ASPDEPR002). Declare each status code withResults<...>and.ProducesProblem(status). Detail, Scalar, and versioning:dev-stack:aspnetcore-openapi.
Never write
| Wrong | Correct |
|---|---|
Startup.cs, WebHost.CreateDefaultBuilder(args) |
WebApplication.CreateBuilder(args) in Program.cs |
services.BuildServiceProvider() to read a setting |
(sp, x) => sp.GetRequiredService<IOptions<T>>().Value |
services.Configure<T>(config.GetSection("X")) without validation |
AddOptions<T>().BindConfiguration("X").ValidateDataAnnotations().ValidateOnStart() |
configuration["Payment:Url"] in a service |
Inject IOptions<PaymentOptions> |
Scoped DbContext in a singleton or BackgroundService constructor |
IServiceScopeFactory.CreateAsyncScope() per unit of work |
Results.Ok(x) and IResult everywhere |
TypedResults.Ok(x) with Results<Ok<T>, NotFound> |
try { } catch (Exception ex) { return StatusCode(500, ex.Message); } |
UseExceptionHandler() and an IExceptionHandler |
Detail = exception.Message |
A fixed title and a stable code |
| Own exception middleware class | IExceptionHandler or StatusCodeSelector |
app.UseDeveloperExceptionPage(); |
Nothing: Development has it by default |
AddFluentValidation(), AddFluentValidationAutoValidation() |
ValidateAsync in an endpoint filter |
using var client = new HttpClient(); in a method |
Typed client from AddHttpClient<T>() |
.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, ...)) |
.AddStandardResilienceHandler() |
services.AddStandardResilienceHandler() |
It extends IHttpClientBuilder: AddHttpClient<T>().AddStandardResilienceHandler() |
| Two resilience handlers on one client | One handler, or RemoveAllResilienceHandlers() first |
Task.Run(() => SendMailAsync()) in a handler |
Channel<T> and a BackgroundService |
while (true) { ...; await Task.Delay(10000); } |
PeriodicTimer with TimeProvider and stoppingToken |
AddSwaggerGen() and .WithOpenApi() in a new .NET 10 API |
AddOpenApi(), MapOpenApi() |
KnownNetworks.Add(new IPNetwork(...)) |
KnownIPNetworks.Add(IPNetwork.Parse("10.0.0.0/8")) |
AllowAnyOrigin() with AllowCredentials() |
WithOrigins(origins) from configuration |
public partial class Program { } for tests |
Not needed in .NET 10 |
MediatR ISender.Send(...), AutoMapper IMapper.Map(...) |
Handler class, manual mapping or Mapperly |
Check
Run the tools in this order. Fix each error. For each warning, fix it or give the reason.
-
Build with the analyzers. Pass: 0 warnings and 0 errors.
dotnet build -warnaserror -
Check the format. Pass: exit code 0.
dotnet format --verify-no-changes -
Run the rule check of this skill. Pass:
stackcheck: 0 errors. In an existing project, add--changed <base branch>.python3 <skill folder>/scripts/stackcheck.py --root <repo> -
Find deprecated and vulnerable packages. Pass: no rows.
dotnet list package --deprecated --vulnerable --include-transitive -
Run the tests. Pass: all green, including one test that starts the host with
ValidateOnBuildand one HTTP test per new endpoint (dev-stack:dotnet-testing).dotnet test
Review checklist
The full list is in references/review-checklist.md.
Program.csusesWebApplication.CreateBuilderorHost.CreateApplicationBuilder. tool (ASPDEPR004, ASPDEPR008, ASP-WEBHOST)- No
BuildServiceProvider()during registration. tool (ASP0000, ASP-BUILD-PROVIDER) - No scoped service in a singleton or hosted service, and
ValidateOnBuildis on. judge - Each options class binds a section, validates it, and uses
ValidateOnStart. tool (ASP-OPTIONS-NO-VALIDATE, ASP-OPTIONS-CONFIGURE-SECTION) - Middleware order matches rule 11. tool (ASP-ORDER-CORS, ASP-ORDER-AUTH, ASP-ORDER-FORWARDED) and judge
- Handlers return
TypedResultswith a declaredResults<...>type. tool (ASP-RESULTS-UNTYPED) - Each handler takes a
CancellationTokenand passes it on. tool (CA2016) and judge - Requests and responses are records, not entities. judge
- Errors are ProblemDetails, and no response contains an exception message. tool (ASP-EXCEPTION-MESSAGE) and judge
- An
IExceptionHandlerthat returnstruelogs the exception. judge - No
new HttpClient(, no typed client in a singleton. tool (ASP-NEW-HTTPCLIENT) and judge - One resilience handler per client, no retry for unsafe methods, no Polly 7. tool (ASP-PKG-HTTP-POLLY, ASP-POLLY-POLICY) and judge
- Liveness has no checks, readiness has the
readychecks. judge - A
BackgroundServiceuses a scope and a catch per iteration and honorsstoppingToken. judge - No deprecated FluentValidation integration, no MediatR, no AutoMapper. tool (ASP-PKG-FV-ASPNETCORE, ASP-FV-AUTOVALIDATION, ASP-PKG-MEDIATR, ASP-PKG-AUTOMAPPER)
Report
End with the report of stack rule 8 (references/stack-rules.md): the same headings in the same order on each run.
References
references/program-template.md: read before you write a newProgram.cs, endpoint group, typed client, exception handler, background service, or worker. All code compiled.references/hosting-di-options.md: read when you register services, bind options, or write a hosted service.references/endpoints-errors.md: read when you write an endpoint, a request or response type, error handling, validation, or JSON settings.references/http-resilience.md: read when the code calls another HTTP API.references/pipeline-wiring.md: read when you add forwarded headers, CORS, authentication, authorization, rate limiting, or health endpoints.references/net11.md: read only when the project targetsnet11.0.references/decisions.md: read when new code needs a decision from the defaults table.references/review-checklist.md: read when you review a change.references/sources.md: the primary sources and the date of each check.references/stack-rules.md: the common rules of each dev-stack skill.references/language.md: the rules for text output.
04 同仓库更多 Skills
web-accessibility
Web accessibility to WCAG 2.2 AA - a checklist for the design, the tool checks (axe-core, the Tab walk, reduced motion), and the manual checks that no tool does (screen reader, zoom, status messages) - with the EAA and EN 301 549 status. Use when a design, mockup, or built feature must be checked for accessibility, when a review must cover keyboard and screen reader use, when the user asks about focus, a focus trap, contrast, or a screen reader on a page, or when the user asks which accessibility rules apply.
ux-states
State inventory for each screen - default, empty, loading, partial, error, success, disabled, overflow, offline, and the business states (no permission, stale data, locked by another user, waiting on an external system, bulk result with failures, read only) - with what the user sees, can do, and how the user recovers. Use when a screen or flow needs its states designed or checked, or when a design shows only the happy path.
ux-setup
Set up a project for UX work - finds the design tools, the design-system source, the brand files, the languages, and the run command, asks the human one round of questions, and writes the "## Design" section of .claude/rules/delivery.md that the ux-design commands and the ux-designer agent read. Moves an older "## Design" section out of CLAUDE.md. Use when /setup, /ux-design, or /ux-review needs the design facts, when the ux-designer agent returns NEEDS_HUMAN because the "## Design" section is missing, or when the user wants to set up or change the design tools of a project.
ux-review
UX review of a built feature against its approved design - Playwright walks each flow and state at 390, 820, and 1440 px, axe-core and the tell checks run on each state, and each heuristic gets a verdict - with findings by owner, severity, and origin, and a verdict in ux-review.md in the work folder of the item. Use when a built feature or screen must be checked against its design, mockups, or prototype, in each state or at each screen size, when built screens need findings by severity, when the build of an item with a UX design is done, or when existing screens need a UX audit.
ux-prototype
Clickable prototype of a designed story in the proto-shell standard, with variants for an A/B test, all states in scope, three sizes, and a test plan with tasks. Use when a design or mockups exist and the team must test the flow or compare variants with users before the build.
ux-practice
The method of the ux-designer agent for the UX design of a story, a feature, or a screen - Double Diamond phases, a design spec with a source for each decision, the UX decision log, evidence tags, severity, and the modes light, full, and new-direction. Preloaded by the ux-designer agent. Use when the ux-designer agent or another UX skill names this method. For the design of an item, a person starts ux-design:ux-design.