[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6DYG1HMPHC364FNK6PXFBX8":3,"skill-same:01M6DYG1HMPHC364FNK6PXFBX8":96},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":50,"linkOnly":51,"markdownContent":52,"markdownBody":53,"frontMatter":54,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":59,"repositoryHtmlUrl":60,"repositoryHomepageUrl":61,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":64,"updatedAt":65,"install":66,"resources":79},"01M6DYG1HMPHC364FNK6PXFBX8","dotnet-webapi",null,"Guides creation and modification of ASP.NET Core Web API endpoints with correct HTTP semantics, OpenAPI metadata, and error handling. USE FOR: adding new API endpoints (controllers or minimal APIs), wiring up OpenAPI\u002FSwagger, creating .http test files, setting up global error handling middleware. DO NOT USE FOR: general C# coding style, EF Core data access or query optimization (use optimizing-ef-core-queries), frontend\u002FBlazor work, gRPC services, or SignalR hubs.","managedcode\u002Fdotnet-skills","managedcode","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F78253589?v=4","01M6DYDJR3EG8KB5G4PC65XCTT","Managed Code","01M6DYDJX0ZT432N04NYJW89DN",515,"MIT","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FFrameworks\u002FOfficial-DotNet-ASPNetCore\u002Fskills\u002Fdotnet-webapi\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49],"dotnet","dotnet webapi","new","frontend","wiring","middleware","error","web api","signalr","guides","creation","swagger","query","do","files","query optimization","up","work","coding","access","api","data","ef core","grpc","blazor","core","2026-11-10 10:12:30",false,"---\nname: dotnet-webapi\ndescription: >\n  Guides creation and modification of ASP.NET Core Web API endpoints with\n  correct HTTP semantics, OpenAPI metadata, and error handling.\n  USE FOR: adding new API endpoints (controllers or minimal APIs), wiring up\n  OpenAPI\u002FSwagger, creating .http test files, setting up global error handling\n  middleware.\n  DO NOT USE FOR: general C# coding style, EF Core data access or query\n  optimization (use optimizing-ef-core-queries), frontend\u002FBlazor work, gRPC\n  services, or SignalR hubs.\nlicense: MIT\n---\n\n# ASP.NET Core Web API\n\nProduce well-structured ASP.NET Core Web API endpoints with proper HTTP\nsemantics, OpenAPI documentation, and error handling.\n\n## When to Use\n\nUse this skill when working on ASP.NET Core HTTP APIs, including:\n\n- adding or modifying Web API endpoints implemented with controllers or minimal APIs;\n- wiring up OpenAPI\u002FSwagger metadata and endpoint documentation;\n- defining request\u002Fresponse DTOs and consistent HTTP status code behavior;\n- adding `.http` files or similar request-based API testing artifacts;\n- configuring centralized API error handling middleware or exception mapping.\n\n## When Not to Use\n\nDo not use this skill for:\n\n- general C# coding style or non-API refactoring;\n- EF Core data modeling or query optimization work; use `optimizing-ef-core-queries`;\n- frontend, Razor, or Blazor UI changes;\n- gRPC services;\n- SignalR hubs or real-time messaging flows.\n\n## Inputs \u002F prerequisites\n\nBefore applying this skill, gather the project context needed to match the\nexisting API style and wiring:\n\n- the ASP.NET Core entry point, typically `Program.cs`;\n- any existing controllers, especially classes inheriting `ControllerBase` or\n  using `[ApiController]`;\n- any existing minimal API registrations such as `app.MapGet`, `app.MapPost`,\n  `app.MapPut`, or `app.MapDelete`;\n- related DTO, model, validation, and error-handling types already used by the project;\n- available build, run, and test commands so changes can be verified.\n\nIf the user asks for a new endpoint, inspect the current project structure first\nso the implementation follows the established conventions rather than mixing styles.\n## Workflow\n\n### Step 1: Determine the API style\n\nScan the project for existing endpoint patterns before writing any code.\n\n1. Search for classes inheriting `ControllerBase` or decorated with `[ApiController]`.\n2. Search `Program.cs` or endpoint files for `app.MapGet`, `app.MapPost`, etc.\n3. If the project already uses **controllers**, continue with controllers.\n4. If the project already uses **minimal APIs**, continue with minimal APIs.\n5. If neither exists (new project), **default to minimal APIs** unless the user\n   explicitly requests controllers.\n\nDo not mix styles in the same project.\n\n### Step 2: Define request and response types\n\nCreate dedicated types for API input and output. Never expose EF Core entities\ndirectly in request or response bodies.\n\n**Use `sealed record` for all DTOs.** Records enforce immutability, provide\nvalue-based equality, and produce concise code. Seal them to prevent unintended\ninheritance and enable JIT devirtualization (CA1852).\n\n**Naming convention:**\n\n| Role | Convention | Example |\n|------|-----------|---------|\n| Input (create) | `Create{Entity}Request` | `CreateProductRequest` |\n| Input (update) | `Update{Entity}Request` | `UpdateProductRequest` |\n| Output (single) | `{Entity}Response` | `ProductResponse` |\n| Output (list) | `{Entity}ListResponse` | `ProductListResponse` |\n\n**XML doc comments on all DTOs:** Add `\u003Csummary>` XML doc comments to every\nrequest and response type exposed in the API. These comments are automatically\nincluded in the generated OpenAPI specification, producing richer documentation\nwithout extra metadata calls.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Fopenapi-comments\n\n**Date and time values — use `DateTimeOffset`:** When a DTO includes a date or\ntime property, always use `DateTimeOffset` instead of `DateTime`.\n`DateTimeOffset` preserves the UTC offset, avoids ambiguous timezone\nconversions, and serializes to ISO 8601 with offset information in JSON — which\nis what API consumers expect.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.datetimeoffset\n**JSON serialization options — preserve existing behavior by default:** For\nexisting APIs, do **not** introduce stricter serialization\u002Fdeserialization settings\nunless the project already uses them or the user explicitly asks for them. Settings\nsuch as case-sensitive property matching and strict number handling can break\nexisting clients. For **new projects**, or when strict JSON handling is explicitly\nrequested, configure options like the following to minimize the potential of\nprocessing malicious requests:\n\n```csharp\n\u002F\u002F Apply these settings only for new projects, when the existing project already\n\u002F\u002F uses them, or when the user explicitly requests stricter JSON behavior.\nbuilder.Services.ConfigureHttpJsonOptions(options =>\n{\n    \u002F\u002F disallow reading numbers from JSON strings\n    options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;\n    \u002F\u002F match properties with exact casing during deserialization\n    options.SerializerOptions.PropertyNameCaseInsensitive = false;\n    \u002F\u002F reject duplicate JSON property names during deserialization\n    options.SerializerOptions.AllowDuplicateProperties = false;\n    \u002F\u002F omit null properties from serialized output\n    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;\n});\n```\n**Enum properties — serialize as strings by default:** Unless the user\nexplicitly requests integer serialization, all enum properties should be\nserialized as strings. String-serialized enums are human-readable, less fragile\nwhen values are reordered, and produce better OpenAPI documentation. See Step 4\nfor the `JsonStringEnumConverter` configuration.\n\n**Response DTOs** — use positional sealed records for concise, immutable output:\n\n```csharp\n\u002F\u002F\u002F \u003Csummary>Represents a product returned by the API.\u003C\u002Fsummary>\npublic sealed record ProductResponse(\n    int Id,\n    string Name,\n    decimal Price,\n    Category Category,\n    bool IsAvailable,\n    DateTimeOffset CreatedAt);\n```\n\n**Request DTOs** — use sealed records with `init` properties so data annotations\nwork naturally:\n\n```csharp\n\u002F\u002F\u002F \u003Csummary>Payload for creating a new product.\u003C\u002Fsummary>\npublic sealed record CreateProductRequest\n{\n    [Required, MaxLength(200)]\n    public required string Name { get; init; }\n\n    [Range(0.01, 999999.99)]\n    public required decimal Price { get; init; }\n\n    public required Category Category { get; init; }\n}\n```\n\nFollow the same pattern for `Update{Entity}Request` records, adding any\nadditional properties the update requires (e.g., `IsAvailable`).\n\n**Minimal API validation — register explicitly:** Data-annotation validation\n(`[Required]`, `[MaxLength]`, `[Range]`, etc.) is automatic in MVC controllers,\nbut minimal APIs require explicit opt-in. For **.NET 10+** projects using minimal\nAPIs, add the validation services in `Program.cs`:\n\n```csharp\nbuilder.Services.AddValidation();\n```\n\nThis wires up an endpoint filter that validates parameters decorated with data\nannotations before the handler executes, returning a `400 Bad Request` with a\nvalidation problem details response on failure.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fminimal-apis?view=aspnetcore-10.0\n\n**Do not** use mutable classes (`{ get; set; }`) for DTOs. Mutable DTOs allow\naccidental modification after construction and lose the self-documenting\nimmutability that records provide.\n\n### Step 3: Implement the endpoints\n\nWhether using controllers or minimal APIs, follow these HTTP conventions\nconsistently.\n\n**Organizing minimal API endpoints:** For projects using minimal APIs, organize\nendpoints by resource using static classes with a static `Map\u003CResource>` method.\nThis pattern keeps endpoint definitions grouped by resource type, making the\ncode more maintainable and easier to navigate as the API grows.\n\n**Pattern structure:**\n\n1. Create one static class per resource (e.g., `ProductEndpoints`, `CategoryEndpoints`).\n2. Define a static `Map\u003CResource>(this WebApplication app)` extension method.\n3. Inside the method, call `MapGet`, `MapPost`, `MapPut`, `MapDelete`, etc. for\n   that resource's endpoints.\n4. In `Program.cs`, call each resource's `Map` method in order.\n\n**Minimal API return types — prefer `TypedResults`:**\n\nAlways prefer `TypedResults` over the `Results` factory. `TypedResults` embeds\nresponse type information in the method signature, giving the OpenAPI generator\nricher metadata automatically.\n\nWhen a handler returns **multiple result types** (e.g., `Ok` or `NotFound`),\nannotate the lambda with an explicit `Results\u003CT1, T2>` return type. This\nlets you use `TypedResults` while still giving the compiler a common type:\n\n```csharp\nasync Task\u003CResults\u003COk\u003CProductResponse>, NotFound>> (int id, ...) => ...\n```\n\n**Do not** use `TypedResults.Ok(x)` and `TypedResults.NotFound()` in a bare\nternary without an explicit return type annotation. `Ok\u003CT>` and `NotFound` are\ndifferent types with no common base the compiler can infer, which causes\n`CS1593: Delegate 'RequestDelegate' does not take N arguments` because the\ncompiler falls back to matching `RequestDelegate(HttpContext)`.\n\n**Fallback — `Results` factory:** If a handler has many conditional branches\n(7+ result types), you may use the `Results` factory (`Results.Ok()`,\n`Results.NotFound()`) which returns `IResult`, sacrificing compile-time OpenAPI\ninference for simpler signatures.\n\n**Status codes:**\n\n| Operation | Success | Common errors |\n|-----------|---------|---------------|\n| GET (single) | `200 OK` | `404 Not Found` |\n| GET (list) | `200 OK` | — |\n| POST (create) | `201 Created` with `Location` header | `400 Bad Request`, `409 Conflict` |\n| PUT (full update) | `200 OK` | `400 Bad Request`, `404 Not Found` |\n| PATCH (partial\u002Faction) | `200 OK` | `400 Bad Request`, `404 Not Found` |\n| DELETE | `204 No Content` | `404 Not Found`, `409 Conflict` |\n\n**POST 201 responses:** Always return a `Location` header pointing to the\nnewly created resource.\n\n- Controllers: use `CreatedAtAction(nameof(GetById), new { id = ... }, response)`\n- Minimal APIs: use `TypedResults.Created($\"\u002Fapi\u002Fproducts\u002F{id}\", response)`\n\n**CancellationToken:** Accept `CancellationToken` in every endpoint signature\nand forward it through to all async calls (service methods, EF Core queries,\n`HttpClient` calls). This allows the server to stop work when a client\ndisconnects.\n\n```csharp\n\u002F\u002F Controller example\n[HttpGet(\"{id}\")]\npublic async Task\u003CActionResult\u003CProductResponse>> GetById(\n    int id, CancellationToken cancellationToken)\n{\n    var product = await _productService.GetByIdAsync(id, cancellationToken);\n    return product is null ? NotFound() : Ok(product);\n}\n\n\u002F\u002F Minimal API example — TypedResults with explicit return type (recommended)\napp.MapGet(\"\u002Fapi\u002Fproducts\u002F{id}\", async Task\u003CResults\u003COk\u003CProductResponse>, NotFound>> (\n    int id, IProductService service, CancellationToken cancellationToken) =>\n{\n    var product = await service.GetByIdAsync(id, cancellationToken);\n    return product is null ? TypedResults.NotFound() : TypedResults.Ok(product);\n});\n```\n\n### Step 4: Wire up OpenAPI\n\nEvery ASP.NET Core Web API should have OpenAPI documentation. Check whether\nthe project already has OpenAPI configured before adding it.\n\n**For .NET 9+ projects**, use the built-in ASP.NET Core OpenAPI support\n(`builder.Services.AddOpenApi()` + `app.MapOpenApi()` in development).\nThis is all that is needed — no additional packages required.\n\n**Do NOT add any `Swashbuckle.*` NuGet package** (`Swashbuckle.AspNetCore`,\n`Swashbuckle.AspNetCore.SwaggerUI`, `Swashbuckle.AspNetCore.SwaggerGen`,\netc.) to .NET 9+ projects. Swashbuckle has known compatibility issues with\n.NET 9+ and .NET 10 OpenAPI types. For projects targeting .NET 8 or earlier,\nSwashbuckle is acceptable. If the project already has Swashbuckle installed,\nkeep it unless the user asks to remove it.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Foverview\n\n**OpenAPI metadata on endpoints:** Add descriptive metadata so the generated\ndocumentation is useful, not just a list of routes. For minimal APIs, chain\nthe metadata methods:\n\n```csharp\napp.MapGet(\"\u002Fapi\u002Fproducts\u002F{id}\", handler)\n    .WithName(\"GetProductById\")\n    .WithSummary(\"Get a product by ID\")\n    .WithDescription(\"Returns the full product details including category.\")\n    .Produces\u003CProductResponse>(StatusCodes.Status200OK)\n    .Produces(StatusCodes.Status404NotFound);\n```\n\n**Enum serialization (strings by default):** Configure JSON serialization so\nenums appear as readable strings in both API responses and OpenAPI schemas.\nAlways add this configuration unless the user explicitly requests integer\nenum serialization. Configure it for both minimal APIs and controllers, as\nthey use different option types:\n\n```csharp\n\u002F\u002F Minimal APIs\nbuilder.Services.ConfigureHttpJsonOptions(options =>\n    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));\n\n\u002F\u002F Controllers \u002F MVC\nbuilder.Services.AddControllers()\n    .AddJsonOptions(options =>\n    {\n        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());\n    });\n```\n\n### Step 5: Set up error handling\n\nUse a global exception handler so that individual endpoints do not need\ntry-catch blocks. Return RFC 7807 Problem Details for all error responses.\n\n**For .NET 8+ projects**, prefer the built-in exception handler middleware:\n\n```csharp\nbuilder.Services.AddProblemDetails();\n\napp.UseExceptionHandler();\napp.UseStatusCodePages();\n```\n\nIf the project needs custom exception-to-status-code mapping (e.g., a\n`NotFoundException` should return 404), implement `IExceptionHandler`:\n\n```csharp\ninternal sealed class ApiExceptionHandler(ILogger\u003CApiExceptionHandler> logger)\n    : IExceptionHandler\n{\n    public async ValueTask\u003Cbool> TryHandleAsync(\n        HttpContext httpContext,\n        Exception exception,\n        CancellationToken cancellationToken)\n    {\n        var (statusCode, title) = exception switch\n        {\n            KeyNotFoundException => (StatusCodes.Status404NotFound, \"Not Found\"),\n            ArgumentException => (StatusCodes.Status400BadRequest, \"Bad Request\"),\n            InvalidOperationException => (StatusCodes.Status409Conflict, \"Conflict\"),\n            _ => (0, (string?)null)\n        };\n\n        if (statusCode == 0)\n            return false; \u002F\u002F Let the default handler deal with it\n\n        \u002F\u002F Important: returning true below suppresses the exception diagnostics middleware\n        \u002F\u002F for this exception, so ensure it is logged\u002Ftelemetrized before returning.\n        logger.LogWarning(exception, \"Handled API exception: {Title}\", title);\n\n        httpContext.Response.StatusCode = statusCode;\n        await httpContext.Response.WriteAsJsonAsync(new ProblemDetails\n        {\n            Status = statusCode,\n            Title = title,\n            \u002F\u002F Do not use exception.Message here — it may leak sensitive internal details.\n            \u002F\u002F Use a safe, user-facing message instead.\n            Detail = title,\n            Instance = httpContext.Request.Path\n        }, cancellationToken);\n\n        return true;\n    }\n}\n```\n\nRegister it:\n\n```csharp\nbuilder.Services.AddExceptionHandler\u003CApiExceptionHandler>();\nbuilder.Services.AddProblemDetails();\n\napp.UseExceptionHandler();\n```\n\n**File placement:** Always place exception handler classes in a `Middleware\u002F`\nfolder to maintain consistent project organization. Do not place them at the\nproject root.\n\n### Step 6: Use a service layer\n\nDo not inject data stores directly into controllers or endpoint handlers.\nCreate a service interface and a sealed implementation class that owns the\ndata access logic and mapping between entities and request\u002Fresponse types.\n\nAlways define an interface for every service — this enables unit testing with\nmocks and follows the Dependency Inversion Principle:\n\n```csharp\n\u002F\u002F Services\u002FIProductService.cs\npublic interface IProductService\n{\n    Task\u003CIReadOnlyList\u003CProductResponse>> GetAllAsync(CancellationToken ct);\n    Task\u003CProductResponse?> GetByIdAsync(int id, CancellationToken ct);\n    Task\u003CProductResponse> CreateAsync(CreateProductRequest request, CancellationToken ct);\n}\n\n\u002F\u002F Services\u002FProductService.cs\npublic sealed class ProductService(...) : IProductService\n{\n    \u002F\u002F Data access logic, entity-to-DTO mapping\n}\n```\n\nRegister with the interface, not the concrete type:\n\n```csharp\n\u002F\u002F In Program.cs\nbuilder.Services.AddScoped\u003CIProductService, ProductService>();\n```\n\nFor EF Core data access patterns (migrations, Fluent API configuration,\n`AsNoTracking`, seed data), see the `optimizing-ef-core-queries` skill.\n\n### Step 7: Create a .http test file\n\nAfter implementing endpoints, create a `.http` file in the project root that\ndemonstrates how to call every new endpoint. This serves as living\ndocumentation and a quick manual test harness.\n\n```http\n@baseUrl = http:\u002F\u002Flocalhost:5000\n\n### Get all products\nGET {{baseUrl}}\u002Fapi\u002Fproducts\n\n### Get product by ID\nGET {{baseUrl}}\u002Fapi\u002Fproducts\u002F1\n\n### Create a product\nPOST {{baseUrl}}\u002Fapi\u002Fproducts\nContent-Type: application\u002Fjson\n\n{\n  \"name\": \"Wireless Mouse\",\n  \"price\": 29.99,\n  \"category\": \"Electronics\"\n}\n\n### Delete a product\nDELETE {{baseUrl}}\u002Fapi\u002Fproducts\u002F1\n```\n\nInclude at least one request per endpoint with realistic bodies. Show error\npaths (e.g., non-existent IDs). Match the port to `launchSettings.json`.\n\n### Step 8: Build and verify\n\n1. Run `dotnet build` — confirm zero errors and zero warnings.\n2. Start the app and verify the OpenAPI document loads (default: `\u002Fopenapi\u002Fv1.json`).\n3. Run the requests in the `.http` file and confirm correct status codes.\n\n## Validation\n\n- [ ] All endpoints return correct HTTP status codes per the table in Step 3\n- [ ] POST endpoints return `201 Created` with a `Location` header\n- [ ] DELETE endpoints return `204 No Content`\n- [ ] Every endpoint signature includes `CancellationToken`\n- [ ] `CancellationToken` is forwarded to all downstream async calls\n- [ ] OpenAPI document is generated and includes all new endpoints\n- [ ] Endpoints have summary\u002Fdescription metadata for OpenAPI\n- [ ] Enum values appear as strings in JSON responses and OpenAPI schemas (unless user explicitly requested integer serialization)\n- [ ] Error responses use RFC 7807 Problem Details format\n- [ ] Domain entities are not exposed directly in API request\u002Fresponse bodies\n- [ ] All API-exposed DTOs have `\u003Csummary>` XML doc comments\n- [ ] Date and time properties use `DateTimeOffset`, not `DateTime`\n- [ ] A `.http` file exists with a request for every new endpoint\n- [ ] `dotnet build` passes with zero errors and zero warnings\n- [ ] All DTOs are `sealed record` types (not mutable classes)\n- [ ] Minimal API handlers use `TypedResults` with explicit `Results\u003CT1, T2>` return types\n- [ ] Every service has a corresponding interface registered in DI\n- [ ] Exception handlers are placed in the `Middleware\u002F` folder\n\n## Common Pitfalls\n\n| Pitfall | Solution |\n|---------|----------|\n| Exposing domain entities as API responses | Create separate `sealed record` request\u002Fresponse types. Entities leak navigation properties and internal fields. |\n| Forgetting `CancellationToken` | Add to every endpoint and forward through the entire async call chain. |\n| Returning `200 OK` from POST create | Return `201 Created` with a `Location` header. |\n| Missing OpenAPI metadata | Chain `.WithName()`, `.WithSummary()`, `.WithDescription()`, `.Produces\u003CT>()` on every endpoint. |\n| Injecting data stores directly into endpoints | Use a service layer with an interface for separation and testability. |\n| Mixing controller and minimal API styles | Pick one per project and be consistent. |\n| `TypedResults` in ternary without explicit return type | `Ok\u003CT>` and `NotFound` have no common base — annotate with `Task\u003CResults\u003COk\u003CT>, NotFound>>` or fall back to `Results` factory. |\n| Using mutable classes for DTOs | Use `sealed record` with positional syntax (responses) or `init` properties (requests). |\n| Registering services without interfaces | Define `IService` and register with `AddScoped\u003CIService, Service>()`. |\n| Adding any `Swashbuckle.*` package to new .NET 9+ projects | Use built-in `AddOpenApi()` + `MapOpenApi()`. Do not add `Swashbuckle.AspNetCore`, `Swashbuckle.AspNetCore.SwaggerUI`, or any other Swashbuckle package. |\n| Missing XML doc comments on DTOs | Add `\u003Csummary>` XML doc comments to every request and response type. These flow into the generated OpenAPI spec automatically. |\n| Using `DateTime` for date\u002Ftime properties | Use `DateTimeOffset` instead — it preserves UTC offset, avoids timezone ambiguity, and serializes correctly in JSON. |\n| Serializing enums as integers | Configure `JsonStringEnumConverter` so enums serialize as strings by default. Only use integer serialization if the user explicitly requests it. |\n\n## More Info\n\n- [ASP.NET Core Web API overview](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Fweb-api\u002F) — fundamental concepts for building Web APIs\n- [OpenAPI in ASP.NET Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Foverview) — built-in OpenAPI support in .NET 9+\n- [OpenAPI from XML comments](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Fopenapi-comments) — how XML doc comments flow into the OpenAPI spec\n- [Minimal APIs overview](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fminimal-apis\u002Foverview) — routing, parameter binding, and response types\n- [Handle errors in ASP.NET Core APIs](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Fweb-api\u002Fhandle-errors) — Problem Details and exception handling\n- [DateTimeOffset](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.datetimeoffset) — preferred type for date\u002Ftime values in APIs\n","# ASP.NET Core Web API\n\nProduce well-structured ASP.NET Core Web API endpoints with proper HTTP\nsemantics, OpenAPI documentation, and error handling.\n\n## When to Use\n\nUse this skill when working on ASP.NET Core HTTP APIs, including:\n\n- adding or modifying Web API endpoints implemented with controllers or minimal APIs;\n- wiring up OpenAPI\u002FSwagger metadata and endpoint documentation;\n- defining request\u002Fresponse DTOs and consistent HTTP status code behavior;\n- adding `.http` files or similar request-based API testing artifacts;\n- configuring centralized API error handling middleware or exception mapping.\n\n## When Not to Use\n\nDo not use this skill for:\n\n- general C# coding style or non-API refactoring;\n- EF Core data modeling or query optimization work; use `optimizing-ef-core-queries`;\n- frontend, Razor, or Blazor UI changes;\n- gRPC services;\n- SignalR hubs or real-time messaging flows.\n\n## Inputs \u002F prerequisites\n\nBefore applying this skill, gather the project context needed to match the\nexisting API style and wiring:\n\n- the ASP.NET Core entry point, typically `Program.cs`;\n- any existing controllers, especially classes inheriting `ControllerBase` or\n  using `[ApiController]`;\n- any existing minimal API registrations such as `app.MapGet`, `app.MapPost`,\n  `app.MapPut`, or `app.MapDelete`;\n- related DTO, model, validation, and error-handling types already used by the project;\n- available build, run, and test commands so changes can be verified.\n\nIf the user asks for a new endpoint, inspect the current project structure first\nso the implementation follows the established conventions rather than mixing styles.\n## Workflow\n\n### Step 1: Determine the API style\n\nScan the project for existing endpoint patterns before writing any code.\n\n1. Search for classes inheriting `ControllerBase` or decorated with `[ApiController]`.\n2. Search `Program.cs` or endpoint files for `app.MapGet`, `app.MapPost`, etc.\n3. If the project already uses **controllers**, continue with controllers.\n4. If the project already uses **minimal APIs**, continue with minimal APIs.\n5. If neither exists (new project), **default to minimal APIs** unless the user\n   explicitly requests controllers.\n\nDo not mix styles in the same project.\n\n### Step 2: Define request and response types\n\nCreate dedicated types for API input and output. Never expose EF Core entities\ndirectly in request or response bodies.\n\n**Use `sealed record` for all DTOs.** Records enforce immutability, provide\nvalue-based equality, and produce concise code. Seal them to prevent unintended\ninheritance and enable JIT devirtualization (CA1852).\n\n**Naming convention:**\n\n| Role | Convention | Example |\n|------|-----------|---------|\n| Input (create) | `Create{Entity}Request` | `CreateProductRequest` |\n| Input (update) | `Update{Entity}Request` | `UpdateProductRequest` |\n| Output (single) | `{Entity}Response` | `ProductResponse` |\n| Output (list) | `{Entity}ListResponse` | `ProductListResponse` |\n\n**XML doc comments on all DTOs:** Add `\u003Csummary>` XML doc comments to every\nrequest and response type exposed in the API. These comments are automatically\nincluded in the generated OpenAPI specification, producing richer documentation\nwithout extra metadata calls.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Fopenapi-comments\n\n**Date and time values — use `DateTimeOffset`:** When a DTO includes a date or\ntime property, always use `DateTimeOffset` instead of `DateTime`.\n`DateTimeOffset` preserves the UTC offset, avoids ambiguous timezone\nconversions, and serializes to ISO 8601 with offset information in JSON — which\nis what API consumers expect.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.datetimeoffset\n**JSON serialization options — preserve existing behavior by default:** For\nexisting APIs, do **not** introduce stricter serialization\u002Fdeserialization settings\nunless the project already uses them or the user explicitly asks for them. Settings\nsuch as case-sensitive property matching and strict number handling can break\nexisting clients. For **new projects**, or when strict JSON handling is explicitly\nrequested, configure options like the following to minimize the potential of\nprocessing malicious requests:\n\n```csharp\n\u002F\u002F Apply these settings only for new projects, when the existing project already\n\u002F\u002F uses them, or when the user explicitly requests stricter JSON behavior.\nbuilder.Services.ConfigureHttpJsonOptions(options =>\n{\n    \u002F\u002F disallow reading numbers from JSON strings\n    options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;\n    \u002F\u002F match properties with exact casing during deserialization\n    options.SerializerOptions.PropertyNameCaseInsensitive = false;\n    \u002F\u002F reject duplicate JSON property names during deserialization\n    options.SerializerOptions.AllowDuplicateProperties = false;\n    \u002F\u002F omit null properties from serialized output\n    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;\n});\n```\n**Enum properties — serialize as strings by default:** Unless the user\nexplicitly requests integer serialization, all enum properties should be\nserialized as strings. String-serialized enums are human-readable, less fragile\nwhen values are reordered, and produce better OpenAPI documentation. See Step 4\nfor the `JsonStringEnumConverter` configuration.\n\n**Response DTOs** — use positional sealed records for concise, immutable output:\n\n```csharp\n\u002F\u002F\u002F \u003Csummary>Represents a product returned by the API.\u003C\u002Fsummary>\npublic sealed record ProductResponse(\n    int Id,\n    string Name,\n    decimal Price,\n    Category Category,\n    bool IsAvailable,\n    DateTimeOffset CreatedAt);\n```\n\n**Request DTOs** — use sealed records with `init` properties so data annotations\nwork naturally:\n\n```csharp\n\u002F\u002F\u002F \u003Csummary>Payload for creating a new product.\u003C\u002Fsummary>\npublic sealed record CreateProductRequest\n{\n    [Required, MaxLength(200)]\n    public required string Name { get; init; }\n\n    [Range(0.01, 999999.99)]\n    public required decimal Price { get; init; }\n\n    public required Category Category { get; init; }\n}\n```\n\nFollow the same pattern for `Update{Entity}Request` records, adding any\nadditional properties the update requires (e.g., `IsAvailable`).\n\n**Minimal API validation — register explicitly:** Data-annotation validation\n(`[Required]`, `[MaxLength]`, `[Range]`, etc.) is automatic in MVC controllers,\nbut minimal APIs require explicit opt-in. For **.NET 10+** projects using minimal\nAPIs, add the validation services in `Program.cs`:\n\n```csharp\nbuilder.Services.AddValidation();\n```\n\nThis wires up an endpoint filter that validates parameters decorated with data\nannotations before the handler executes, returning a `400 Bad Request` with a\nvalidation problem details response on failure.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fminimal-apis?view=aspnetcore-10.0\n\n**Do not** use mutable classes (`{ get; set; }`) for DTOs. Mutable DTOs allow\naccidental modification after construction and lose the self-documenting\nimmutability that records provide.\n\n### Step 3: Implement the endpoints\n\nWhether using controllers or minimal APIs, follow these HTTP conventions\nconsistently.\n\n**Organizing minimal API endpoints:** For projects using minimal APIs, organize\nendpoints by resource using static classes with a static `Map\u003CResource>` method.\nThis pattern keeps endpoint definitions grouped by resource type, making the\ncode more maintainable and easier to navigate as the API grows.\n\n**Pattern structure:**\n\n1. Create one static class per resource (e.g., `ProductEndpoints`, `CategoryEndpoints`).\n2. Define a static `Map\u003CResource>(this WebApplication app)` extension method.\n3. Inside the method, call `MapGet`, `MapPost`, `MapPut`, `MapDelete`, etc. for\n   that resource's endpoints.\n4. In `Program.cs`, call each resource's `Map` method in order.\n\n**Minimal API return types — prefer `TypedResults`:**\n\nAlways prefer `TypedResults` over the `Results` factory. `TypedResults` embeds\nresponse type information in the method signature, giving the OpenAPI generator\nricher metadata automatically.\n\nWhen a handler returns **multiple result types** (e.g., `Ok` or `NotFound`),\nannotate the lambda with an explicit `Results\u003CT1, T2>` return type. This\nlets you use `TypedResults` while still giving the compiler a common type:\n\n```csharp\nasync Task\u003CResults\u003COk\u003CProductResponse>, NotFound>> (int id, ...) => ...\n```\n\n**Do not** use `TypedResults.Ok(x)` and `TypedResults.NotFound()` in a bare\nternary without an explicit return type annotation. `Ok\u003CT>` and `NotFound` are\ndifferent types with no common base the compiler can infer, which causes\n`CS1593: Delegate 'RequestDelegate' does not take N arguments` because the\ncompiler falls back to matching `RequestDelegate(HttpContext)`.\n\n**Fallback — `Results` factory:** If a handler has many conditional branches\n(7+ result types), you may use the `Results` factory (`Results.Ok()`,\n`Results.NotFound()`) which returns `IResult`, sacrificing compile-time OpenAPI\ninference for simpler signatures.\n\n**Status codes:**\n\n| Operation | Success | Common errors |\n|-----------|---------|---------------|\n| GET (single) | `200 OK` | `404 Not Found` |\n| GET (list) | `200 OK` | — |\n| POST (create) | `201 Created` with `Location` header | `400 Bad Request`, `409 Conflict` |\n| PUT (full update) | `200 OK` | `400 Bad Request`, `404 Not Found` |\n| PATCH (partial\u002Faction) | `200 OK` | `400 Bad Request`, `404 Not Found` |\n| DELETE | `204 No Content` | `404 Not Found`, `409 Conflict` |\n\n**POST 201 responses:** Always return a `Location` header pointing to the\nnewly created resource.\n\n- Controllers: use `CreatedAtAction(nameof(GetById), new { id = ... }, response)`\n- Minimal APIs: use `TypedResults.Created($\"\u002Fapi\u002Fproducts\u002F{id}\", response)`\n\n**CancellationToken:** Accept `CancellationToken` in every endpoint signature\nand forward it through to all async calls (service methods, EF Core queries,\n`HttpClient` calls). This allows the server to stop work when a client\ndisconnects.\n\n```csharp\n\u002F\u002F Controller example\n[HttpGet(\"{id}\")]\npublic async Task\u003CActionResult\u003CProductResponse>> GetById(\n    int id, CancellationToken cancellationToken)\n{\n    var product = await _productService.GetByIdAsync(id, cancellationToken);\n    return product is null ? NotFound() : Ok(product);\n}\n\n\u002F\u002F Minimal API example — TypedResults with explicit return type (recommended)\napp.MapGet(\"\u002Fapi\u002Fproducts\u002F{id}\", async Task\u003CResults\u003COk\u003CProductResponse>, NotFound>> (\n    int id, IProductService service, CancellationToken cancellationToken) =>\n{\n    var product = await service.GetByIdAsync(id, cancellationToken);\n    return product is null ? TypedResults.NotFound() : TypedResults.Ok(product);\n});\n```\n\n### Step 4: Wire up OpenAPI\n\nEvery ASP.NET Core Web API should have OpenAPI documentation. Check whether\nthe project already has OpenAPI configured before adding it.\n\n**For .NET 9+ projects**, use the built-in ASP.NET Core OpenAPI support\n(`builder.Services.AddOpenApi()` + `app.MapOpenApi()` in development).\nThis is all that is needed — no additional packages required.\n\n**Do NOT add any `Swashbuckle.*` NuGet package** (`Swashbuckle.AspNetCore`,\n`Swashbuckle.AspNetCore.SwaggerUI`, `Swashbuckle.AspNetCore.SwaggerGen`,\netc.) to .NET 9+ projects. Swashbuckle has known compatibility issues with\n.NET 9+ and .NET 10 OpenAPI types. For projects targeting .NET 8 or earlier,\nSwashbuckle is acceptable. If the project already has Swashbuckle installed,\nkeep it unless the user asks to remove it.\n\nReference: https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Foverview\n\n**OpenAPI metadata on endpoints:** Add descriptive metadata so the generated\ndocumentation is useful, not just a list of routes. For minimal APIs, chain\nthe metadata methods:\n\n```csharp\napp.MapGet(\"\u002Fapi\u002Fproducts\u002F{id}\", handler)\n    .WithName(\"GetProductById\")\n    .WithSummary(\"Get a product by ID\")\n    .WithDescription(\"Returns the full product details including category.\")\n    .Produces\u003CProductResponse>(StatusCodes.Status200OK)\n    .Produces(StatusCodes.Status404NotFound);\n```\n\n**Enum serialization (strings by default):** Configure JSON serialization so\nenums appear as readable strings in both API responses and OpenAPI schemas.\nAlways add this configuration unless the user explicitly requests integer\nenum serialization. Configure it for both minimal APIs and controllers, as\nthey use different option types:\n\n```csharp\n\u002F\u002F Minimal APIs\nbuilder.Services.ConfigureHttpJsonOptions(options =>\n    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));\n\n\u002F\u002F Controllers \u002F MVC\nbuilder.Services.AddControllers()\n    .AddJsonOptions(options =>\n    {\n        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());\n    });\n```\n\n### Step 5: Set up error handling\n\nUse a global exception handler so that individual endpoints do not need\ntry-catch blocks. Return RFC 7807 Problem Details for all error responses.\n\n**For .NET 8+ projects**, prefer the built-in exception handler middleware:\n\n```csharp\nbuilder.Services.AddProblemDetails();\n\napp.UseExceptionHandler();\napp.UseStatusCodePages();\n```\n\nIf the project needs custom exception-to-status-code mapping (e.g., a\n`NotFoundException` should return 404), implement `IExceptionHandler`:\n\n```csharp\ninternal sealed class ApiExceptionHandler(ILogger\u003CApiExceptionHandler> logger)\n    : IExceptionHandler\n{\n    public async ValueTask\u003Cbool> TryHandleAsync(\n        HttpContext httpContext,\n        Exception exception,\n        CancellationToken cancellationToken)\n    {\n        var (statusCode, title) = exception switch\n        {\n            KeyNotFoundException => (StatusCodes.Status404NotFound, \"Not Found\"),\n            ArgumentException => (StatusCodes.Status400BadRequest, \"Bad Request\"),\n            InvalidOperationException => (StatusCodes.Status409Conflict, \"Conflict\"),\n            _ => (0, (string?)null)\n        };\n\n        if (statusCode == 0)\n            return false; \u002F\u002F Let the default handler deal with it\n\n        \u002F\u002F Important: returning true below suppresses the exception diagnostics middleware\n        \u002F\u002F for this exception, so ensure it is logged\u002Ftelemetrized before returning.\n        logger.LogWarning(exception, \"Handled API exception: {Title}\", title);\n\n        httpContext.Response.StatusCode = statusCode;\n        await httpContext.Response.WriteAsJsonAsync(new ProblemDetails\n        {\n            Status = statusCode,\n            Title = title,\n            \u002F\u002F Do not use exception.Message here — it may leak sensitive internal details.\n            \u002F\u002F Use a safe, user-facing message instead.\n            Detail = title,\n            Instance = httpContext.Request.Path\n        }, cancellationToken);\n\n        return true;\n    }\n}\n```\n\nRegister it:\n\n```csharp\nbuilder.Services.AddExceptionHandler\u003CApiExceptionHandler>();\nbuilder.Services.AddProblemDetails();\n\napp.UseExceptionHandler();\n```\n\n**File placement:** Always place exception handler classes in a `Middleware\u002F`\nfolder to maintain consistent project organization. Do not place them at the\nproject root.\n\n### Step 6: Use a service layer\n\nDo not inject data stores directly into controllers or endpoint handlers.\nCreate a service interface and a sealed implementation class that owns the\ndata access logic and mapping between entities and request\u002Fresponse types.\n\nAlways define an interface for every service — this enables unit testing with\nmocks and follows the Dependency Inversion Principle:\n\n```csharp\n\u002F\u002F Services\u002FIProductService.cs\npublic interface IProductService\n{\n    Task\u003CIReadOnlyList\u003CProductResponse>> GetAllAsync(CancellationToken ct);\n    Task\u003CProductResponse?> GetByIdAsync(int id, CancellationToken ct);\n    Task\u003CProductResponse> CreateAsync(CreateProductRequest request, CancellationToken ct);\n}\n\n\u002F\u002F Services\u002FProductService.cs\npublic sealed class ProductService(...) : IProductService\n{\n    \u002F\u002F Data access logic, entity-to-DTO mapping\n}\n```\n\nRegister with the interface, not the concrete type:\n\n```csharp\n\u002F\u002F In Program.cs\nbuilder.Services.AddScoped\u003CIProductService, ProductService>();\n```\n\nFor EF Core data access patterns (migrations, Fluent API configuration,\n`AsNoTracking`, seed data), see the `optimizing-ef-core-queries` skill.\n\n### Step 7: Create a .http test file\n\nAfter implementing endpoints, create a `.http` file in the project root that\ndemonstrates how to call every new endpoint. This serves as living\ndocumentation and a quick manual test harness.\n\n```http\n@baseUrl = http:\u002F\u002Flocalhost:5000\n\n### Get all products\nGET {{baseUrl}}\u002Fapi\u002Fproducts\n\n### Get product by ID\nGET {{baseUrl}}\u002Fapi\u002Fproducts\u002F1\n\n### Create a product\nPOST {{baseUrl}}\u002Fapi\u002Fproducts\nContent-Type: application\u002Fjson\n\n{\n  \"name\": \"Wireless Mouse\",\n  \"price\": 29.99,\n  \"category\": \"Electronics\"\n}\n\n### Delete a product\nDELETE {{baseUrl}}\u002Fapi\u002Fproducts\u002F1\n```\n\nInclude at least one request per endpoint with realistic bodies. Show error\npaths (e.g., non-existent IDs). Match the port to `launchSettings.json`.\n\n### Step 8: Build and verify\n\n1. Run `dotnet build` — confirm zero errors and zero warnings.\n2. Start the app and verify the OpenAPI document loads (default: `\u002Fopenapi\u002Fv1.json`).\n3. Run the requests in the `.http` file and confirm correct status codes.\n\n## Validation\n\n- [ ] All endpoints return correct HTTP status codes per the table in Step 3\n- [ ] POST endpoints return `201 Created` with a `Location` header\n- [ ] DELETE endpoints return `204 No Content`\n- [ ] Every endpoint signature includes `CancellationToken`\n- [ ] `CancellationToken` is forwarded to all downstream async calls\n- [ ] OpenAPI document is generated and includes all new endpoints\n- [ ] Endpoints have summary\u002Fdescription metadata for OpenAPI\n- [ ] Enum values appear as strings in JSON responses and OpenAPI schemas (unless user explicitly requested integer serialization)\n- [ ] Error responses use RFC 7807 Problem Details format\n- [ ] Domain entities are not exposed directly in API request\u002Fresponse bodies\n- [ ] All API-exposed DTOs have `\u003Csummary>` XML doc comments\n- [ ] Date and time properties use `DateTimeOffset`, not `DateTime`\n- [ ] A `.http` file exists with a request for every new endpoint\n- [ ] `dotnet build` passes with zero errors and zero warnings\n- [ ] All DTOs are `sealed record` types (not mutable classes)\n- [ ] Minimal API handlers use `TypedResults` with explicit `Results\u003CT1, T2>` return types\n- [ ] Every service has a corresponding interface registered in DI\n- [ ] Exception handlers are placed in the `Middleware\u002F` folder\n\n## Common Pitfalls\n\n| Pitfall | Solution |\n|---------|----------|\n| Exposing domain entities as API responses | Create separate `sealed record` request\u002Fresponse types. Entities leak navigation properties and internal fields. |\n| Forgetting `CancellationToken` | Add to every endpoint and forward through the entire async call chain. |\n| Returning `200 OK` from POST create | Return `201 Created` with a `Location` header. |\n| Missing OpenAPI metadata | Chain `.WithName()`, `.WithSummary()`, `.WithDescription()`, `.Produces\u003CT>()` on every endpoint. |\n| Injecting data stores directly into endpoints | Use a service layer with an interface for separation and testability. |\n| Mixing controller and minimal API styles | Pick one per project and be consistent. |\n| `TypedResults` in ternary without explicit return type | `Ok\u003CT>` and `NotFound` have no common base — annotate with `Task\u003CResults\u003COk\u003CT>, NotFound>>` or fall back to `Results` factory. |\n| Using mutable classes for DTOs | Use `sealed record` with positional syntax (responses) or `init` properties (requests). |\n| Registering services without interfaces | Define `IService` and register with `AddScoped\u003CIService, Service>()`. |\n| Adding any `Swashbuckle.*` package to new .NET 9+ projects | Use built-in `AddOpenApi()` + `MapOpenApi()`. Do not add `Swashbuckle.AspNetCore`, `Swashbuckle.AspNetCore.SwaggerUI`, or any other Swashbuckle package. |\n| Missing XML doc comments on DTOs | Add `\u003Csummary>` XML doc comments to every request and response type. These flow into the generated OpenAPI spec automatically. |\n| Using `DateTime` for date\u002Ftime properties | Use `DateTimeOffset` instead — it preserves UTC offset, avoids timezone ambiguity, and serializes correctly in JSON. |\n| Serializing enums as integers | Configure `JsonStringEnumConverter` so enums serialize as strings by default. Only use integer serialization if the user explicitly requests it. |\n\n## More Info\n\n- [ASP.NET Core Web API overview](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Fweb-api\u002F) — fundamental concepts for building Web APIs\n- [OpenAPI in ASP.NET Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Foverview) — built-in OpenAPI support in .NET 9+\n- [OpenAPI from XML comments](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fopenapi\u002Fopenapi-comments) — how XML doc comments flow into the OpenAPI spec\n- [Minimal APIs overview](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Ffundamentals\u002Fminimal-apis\u002Foverview) — routing, parameter binding, and response types\n- [Handle errors in ASP.NET Core APIs](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Faspnet\u002Fcore\u002Fweb-api\u002Fhandle-errors) — Problem Details and exception handling\n- [DateTimeOffset](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.datetimeoffset) — preferred type for date\u002Ftime values in APIs\n",{"name":5,"license":15,"description":55},"Guides creation and modification of ASP.NET Core Web API endpoints with correct HTTP semantics, OpenAPI metadata, and error handling. USE FOR: adding new API endpoints (controllers or minimal APIs), wiring up OpenAPI\u002FSwagger, creating .http test files, setting up global error handling middleware. DO NOT USE FOR: general C# coding style, EF Core data access or query optimization (use optimizing-ef-core-queries), frontend\u002FBlazor work, gRPC services, or SignalR hubs.\n","main","497cc9aba79a931ac6fb8d36a48cc22fe3d6d74b","catalog\u002FFrameworks\u002FOfficial-DotNet-ASPNetCore\u002Fskills\u002Fdotnet-webapi",41,"https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills","https:\u002F\u002Fskills.managed-code.com","https:\u002F\u002Fgithub.com\u002Fmanagedcode","https:\u002F\u002Fwww.managed-code.com","Open Source Community for .NET Developers: Reliable, Actively Maintained, and Community-Driven. Made in Ukraine 🇺🇦 with ❤️","2026-11-14 19:05:44",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add managedcode\u002Fdotnet-skills --skill dotnet-webapi",{"tool":72,"command":73},"bunx","bunx skills add managedcode\u002Fdotnet-skills --skill dotnet-webapi",{"tool":75,"command":76},"pnpm","pnpm dlx skills add managedcode\u002Fdotnet-skills --skill dotnet-webapi","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FFrameworks\u002FOfficial-DotNet-ASPNetCore\u002Fskills\u002Fdotnet-webapi\u002FSKILL.md",true,[80,86,90],{"path":81,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":84,"sourceHtmlUrl":85},"manifest.json","REFERENCE","参考文档",114,"https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FFrameworks\u002FOfficial-DotNet-ASPNetCore\u002Fskills\u002Fdotnet-webapi\u002Fmanifest.json",{"path":87,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":88,"sourceHtmlUrl":89},"README.md",2616,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__Interstellar-code--sql-cli\u002FREADME.md",{"path":91,"resourceType":92,"resourceTypeDesc":93,"sizeBytes":94,"sourceHtmlUrl":95},"sql-cli.sh","SCRIPT","脚本",7563,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__Interstellar-code--sql-cli\u002Fsql-cli.sh",[97,129,152,184,194,221],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":111,"publishedAt":50},"01M6DYQE1Y9FHAQHEDTVFQ3447","xtwitter-scraper","Use XTwitterScraper when a .NET application needs typed access to Xquik's X automation REST API for tweet search, user lookup, posting workflows, extraction jobs, monitors, webhooks, or giveaway draws. USE FOR: integrating the XTwitterScraper NuGet package; reviewing Xquik API client usage; modeling API-key configuration, pagination, binary exports, raw responses, retries, and webhook\u002Fevent flows in .NET. DO NOT USE FOR: unrelated stacks; direct browser automation; generic social-media strategy; or code that does not call Xquik. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FLibraries\u002FXTwitterScraper\u002Fskills\u002Fxtwitter-scraper\u002FSKILL.md",[103,106],{"categoryNo":104,"categoryName":105,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":107,"categoryName":108,"taxonomyType":109,"taxonomyTypeDesc":110},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[112,113,114,115,116,117,118,119,44,120,121,43,122,123,124,38,125,126,127,128],"xtwitter scraper","browser automation","workflows","run","code","browser","search","repository","Media","api client","edit","unrelated","webhooks","social","commands","modeling","webhook",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":141,"publishedAt":50},"01M6DYQ9S4PE1H6G8MCH9T21HR","sep","Use Sep for high-performance separated-value parsing and writing in .NET, including delimiter inference, explicit parser\u002Fwriter options, and low-allocation row\u002Fcolumn workflows. USE FOR: delimited data needs are performance-sensitive and allocation-aware; project needs explicit control over separator inference, escaping, trimming, and header behavior;. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FLibraries\u002FSep\u002Fskills\u002Fsep\u002FSKILL.md",[135,138],{"categoryNo":136,"categoryName":137,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":139,"categoryName":140,"taxonomyType":109,"taxonomyTypeDesc":110},"01JBSEEDCAT000000000000036","内容创作者",[131,142,143,114,144,115,119,45,145,146,122,147,123,38,37,148,149,150,126,151],"writing","performance","tasks","parsing","parser","context","writer","options","project","high-performance",{"skillNo":153,"name":154,"nameZh":6,"description":155,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":156,"categories":157,"keywords":158,"publishedAt":50},"01M6DZS2DNEPXCGGF6SSCW6G5V","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fwebgpu-claude-skill\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183],"webgpu","threejs","webgpu threejs tsl","setup","shaders","gpu","integration","applications","js","node","syntax","guide","use","language","three","compute","post","processing","with","renderer","for","materials","wgsl","effects","when",{"skillNo":185,"name":186,"nameZh":6,"description":187,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":188,"categories":189,"keywords":190,"publishedAt":50},"01M6DZS0BQXW2B56A289XF1X76","roslynk","Use Roslynk for semantic inspection and edits of *.cs, *.razor and *.cshtml solution files.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Froslynk\u002Fskills\u002Froslynk\u002FSKILL.md",[],[186,171,38,191,192,179,193],"semantic","razor","inspection",{"skillNo":195,"name":196,"nameZh":6,"description":197,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":198,"categories":199,"keywords":200,"publishedAt":50},"01M6DZRW6MEJCVW80K3S4XV60K","system-text-json-net11","Imperative guidance for the System.Text.Json APIs added in .NET 11: the built-in `JsonNamingPolicy.PascalCase` naming policy, and the strongly-typed generic `JsonSerializerOptions.GetTypeInfo` and `JsonSerializerOptions.TryGetTypeInfo` metadata accessors (generic overloads that return a typed `JsonTypeInfo`). USE ONLY when the user is targeting net11.0 or later and needs PascalCase JSON property or dictionary-key names without writing a custom naming policy, a strongly-typed generic `JsonTypeInfo` instead of the non-generic `JsonTypeInfo`, or a no-throw way to probe whether a type's serialization metadata is resolved. DO NOT USE when the target is earlier than net11.0, the requested behavior uses an established pre-net11 naming policy, or the user explicitly selected another JSON library.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fsystem-text-json-net11\u002FSKILL.md",[],[201,202,203,204,142,205,206,207,208,209,210,171,211,212,213,214,37,215,216,217,218,179,219,220,183],"system","json","text","system text json net11","policy","metadata","library","serialization","behavior","user","only","probe","guidance","later","type","dictionary","naming","targeting","custom","generic",{"skillNo":222,"name":223,"nameZh":6,"description":224,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":225,"categories":226,"keywords":229,"publishedAt":50},"01M6DZRRJP3S662NFSG1RSPQQ7","process-api-net11","Provides guidance on the new System.Diagnostics.Process APIs introduced in .NET 11: Process.Run, Process.RunAndCaptureText, Process.StartAndForget, Process.ReadAllText\u002FBytes\u002FLines, KillOnParentExit, InheritedHandles, and StartDetached. USE FOR: starting, orchestrating, or capturing output from external processes in applications targeting net11.0 or later. DO NOT USE FOR: applications targeting .NET 10 or earlier, or basic pre-.NET 11 Process.Start usage without new APIs.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fprocess-api-net11\u002FSKILL.md",[227,228],{"categoryNo":104,"categoryName":105,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":107,"categoryName":108,"taxonomyType":109,"taxonomyTypeDesc":110},[44,230,231,232,115,233,166,201,171,213,214,37,234,235,236,237,218,179,26],"process","process api net11","diagnostics","start","basic","processes","output","usage"]