aspnet-core-apis
ASP.NET Core API development with minimal APIs, controllers, middleware, OpenAPI, and best practices
What this skill does
# ASP.NET Core API Development
## Minimal APIs (.NET 10 Preferred)
### Endpoint Groups
```csharp
public static class ProductEndpoints
{
public static RouteGroupBuilder MapProductEndpoints(this WebApplication app)
{
var group = app.MapGroup("/api/products")
.WithTags("Products")
.RequireAuthorization();
group.MapGet("/", GetAll);
group.MapGet("/{id:int}", GetById);
group.MapPost("/", Create);
group.MapPut("/{id:int}", Update);
group.MapDelete("/{id:int}", Delete);
return group;
}
private static async Task<IResult> GetAll(
[AsParameters] ProductQuery query,
IProductService service,
CancellationToken ct) =>
TypedResults.Ok(await service.GetAllAsync(query, ct));
private static async Task<IResult> GetById(int id, IProductService service, CancellationToken ct) =>
await service.GetByIdAsync(id, ct) is { } product
? TypedResults.Ok(product)
: TypedResults.NotFound();
}
```
### Program.cs Registration
```csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.AddOutputCache();
builder.Services.AddRateLimiter(opts => opts.AddFixedWindowLimiter("api", o =>
{
o.Window = TimeSpan.FromMinutes(1);
o.PermitLimit = 100;
}));
var app = builder.Build();
app.UseOutputCache();
app.UseRateLimiter();
app.MapOpenApi();
app.MapProductEndpoints();
app.MapOrderEndpoints();
app.Run();
```
## Middleware Pipeline
```
Request → UseExceptionHandler → UseHsts → UseHttpsRedirection
→ UseStaticFiles → UseRouting → UseCors → UseAuthentication
→ UseAuthorization → UseOutputCache → UseRateLimiter → Endpoints
```
### Custom Middleware
```csharp
public sealed class RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
var sw = Stopwatch.StartNew();
try
{
await next(context);
}
finally
{
sw.Stop();
logger.LogInformation("Request {Method} {Path} completed in {Elapsed}ms",
context.Request.Method, context.Request.Path, sw.ElapsedMilliseconds);
}
}
}
// Register: app.UseMiddleware<RequestTimingMiddleware>();
```
## Endpoint Filters
```csharp
public sealed class ValidationFilter<T> : IEndpointFilter where T : class
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
var validator = context.HttpContext.RequestServices.GetService<IValidator<T>>();
if (validator is null) return await next(context);
var model = context.GetArgument<T>(0);
var result = await validator.ValidateAsync(model);
return result.IsValid
? await next(context)
: TypedResults.ValidationProblem(result.ToDictionary());
}
}
```
## OpenAPI / Swagger
```csharp
// .NET 10 built-in OpenAPI
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((doc, ctx, ct) =>
{
doc.Info.Title = "My API";
doc.Info.Version = "v1";
return Task.CompletedTask;
});
});
app.MapOpenApi(); // Serves at /openapi/v1.json
app.MapScalarApiReference(); // Interactive API explorer UI
```
## Error Handling
```csharp
// Global exception handler with Problem Details
builder.Services.AddProblemDetails();
app.UseExceptionHandler(error =>
{
error.Run(async context =>
{
var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
var problem = exception switch
{
NotFoundException => new ProblemDetails
{
Status = 404, Title = "Not Found", Detail = exception.Message
},
ValidationException ve => new ProblemDetails
{
Status = 400, Title = "Validation Error",
Extensions = { ["errors"] = ve.Errors }
},
_ => new ProblemDetails
{
Status = 500, Title = "Internal Server Error"
}
};
context.Response.StatusCode = problem.Status ?? 500;
await context.Response.WriteAsJsonAsync(problem);
});
});
```
## Rate Limiting (from official docs)
```csharp
builder.Services.AddRateLimiter(options =>
{
// Fixed Window - simple time-based limit
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.PermitLimit = 4;
opt.Window = TimeSpan.FromSeconds(12);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
});
// Sliding Window - smoother rate control
options.AddSlidingWindowLimiter("sliding", opt =>
{
opt.PermitLimit = 100;
opt.Window = TimeSpan.FromSeconds(30);
opt.SegmentsPerWindow = 3;
});
// Token Bucket - burst-friendly
options.AddTokenBucketLimiter("token", opt =>
{
opt.TokenLimit = 100;
opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
opt.TokensPerPeriod = 20;
opt.AutoReplenishment = true;
});
// Concurrency - limits concurrent requests, not rate
options.AddConcurrencyLimiter("concurrency", opt =>
{
opt.PermitLimit = 50;
opt.QueueLimit = 10;
});
// Custom rejection response
options.OnRejected = async (context, ct) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
await context.HttpContext.Response.WriteAsync("Rate limit exceeded.", ct);
};
});
// IMPORTANT: UseRouting MUST come before UseRateLimiter for endpoint-specific limiters
app.UseRouting();
app.UseRateLimiter();
// Apply to endpoints
app.MapGet("/api/limited", () => "OK").RequireRateLimiting("fixed");
// Partitioned by API key with tiered limits
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
{
string apiKey = context.Request.Headers["X-API-Key"].ToString() ?? "default";
return apiKey switch
{
"premium-key" => RateLimitPartition.GetFixedWindowLimiter(apiKey,
_ => new FixedWindowRateLimiterOptions { PermitLimit = 1000, Window = TimeSpan.FromMinutes(1) }),
_ => RateLimitPartition.GetFixedWindowLimiter(apiKey,
_ => new FixedWindowRateLimiterOptions { PermitLimit = 100, Window = TimeSpan.FromMinutes(1) })
};
});
```
## Dependency Injection Patterns (from official docs)
```csharp
// Lifetimes
builder.Services.AddTransient<ITransientService, TransientService>(); // New each time
builder.Services.AddScoped<IScopedService, ScopedService>(); // Per request
builder.Services.AddSingleton<ISingletonService, SingletonService>(); // Once
// Factory registration
builder.Services.AddScoped<IMyService>(sp =>
new MyService(sp.GetRequiredService<IDependency>()));
// Keyed services (multiple implementations of same interface)
builder.Services.AddKeyedSingleton<ICache, RedisCache>("redis");
builder.Services.AddKeyedSingleton<ICache, MemoryCache>("memory");
// Inject keyed service in minimal API
app.MapGet("/data", ([FromKeyedServices("redis")] ICache cache) => cache.Get("key"));
// Extension method pattern for clean DI registration
public static class MyServiceExtensions
{
public static IServiceCollection AddMyServices(this IServiceCollection services, IConfiguration config)
{
services.Configure<MyOptions>(config.GetSection("MyOptions"));
services.AddScoped<IMyService, MyService>();
return services;
}
}
```
## Middleware Pipeline Order (from official docs)
```csharp
// Correct order for ASP.NET Core 10:
if (app.Environment.IsDevelopment())
app.Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.