ASP.NET Core Quick Reference
Minimal APIs
// Basic endpoint
app.MapGet("/api/products", () => Results.Ok(products));
// With parameters
app.MapGet("/api/products/{id:int}", (int id) => { });
// With DI
app.MapGet("/api/products", (IProductService service) => service.GetAll());
// Route groups
var api = app.MapGroup("/api/products")
.WithTags("Products")
.RequireAuthorization();
Dependency Injection
// Registration
builder.Services.AddTransient<IService, Service>(); // New each time
builder.Services.AddScoped<IService, Service>(); // One per request
builder.Services.AddSingleton<IService, Service>(); // One for app lifetime
// Usage
public class MyController
{
private readonly IService _service;
public MyController(IService service)
{
_service = service;
}
}
Middleware Pipeline
app.UseHttpsRedirection(); // 1. HTTPS redirect
app.UseRouting(); // 2. Match endpoint
app.UseCors(); // 3. CORS
app.UseAuthentication(); // 4. Who are you?
app.UseAuthorization(); // 5. What can you do?
app.UseRateLimiter(); // 6. Rate limit
app.MapControllers(); // 7. Execute
Configuration
// appsettings.json
{
"ApiSettings": {
"ApiKey": "secret",
"Timeout": 30
}
}
// Registration
builder.Services.Configure<ApiSettings>(
builder.Configuration.GetSection("ApiSettings"));
// Usage
public class MyService
{
private readonly ApiSettings _settings;
public MyService(IOptions<ApiSettings> options)
{
_settings = options.Value;
}
}
HTTP Status Codes
| Code | Use |
|---|---|
| 200 | OK (GET, PUT, PATCH) |
| 201 | Created (POST) |
| 204 | No Content (DELETE) |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Server Error |
Endpoint Filters
app.MapPost("/api/products", CreateProduct)
.AddEndpointFilter(async (context, next) =>
{
// Validation logic
return await next(context);
});
Rate Limiting
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.Window = TimeSpan.FromSeconds(10);
opt.PermitLimit = 5;
});
});
app.UseRateLimiter();
app.MapGet("/api/products", GetAll).RequireRateLimiting("fixed");
Model Validation
public class Product
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Range(0.01, 10000)]
public decimal Price { get; set; }
}
Controller Actions
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok(products);
[HttpGet("{id}")]
public IActionResult Get(int id) => Ok(product);
[HttpPost]
public IActionResult Create(Product product)
=> CreatedAtAction(nameof(Get), new { id }, product);
}