Quick Reference Cards


Card 1: Request Pipeline & Middleware Order

Standard Middleware Pipeline Order

┌─────────────────────────────────────────────────┐
│ HTTP Request                                     │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 1. Exception Handler (Global Error Handling)    │
│    app.UseExceptionHandler()                     │
│    OR app.UseDeveloperExceptionPage() (Dev)     │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 2. HSTS (HTTP Strict Transport Security)        │
│    app.UseHsts()                                 │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 3. HTTPS Redirection                             │
│    app.UseHttpsRedirection()                     │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 4. Static Files (wwwroot)                        │
│    app.UseStaticFiles()                          │
│    ⚡ Short-circuits if file found              │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 5. Routing                                       │
│    app.UseRouting()                              │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 6. CORS (Cross-Origin Resource Sharing)         │
│    app.UseCors()                                 │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 7. Authentication (Who are you?)                 │
│    app.UseAuthentication()                       │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 8. Authorization (What can you do?)              │
│    app.UseAuthorization()                        │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 9. Session (if needed)                           │
│    app.UseSession()                              │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 10. Custom Middleware                            │
│     app.UseMyCustomMiddleware()                  │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 11. Response Caching                             │
│     app.UseResponseCaching()                     │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ 12. Endpoints (Controllers/Minimal APIs)         │
│     app.MapControllers()                         │
│     app.MapGet("/api/users", ...)                │
└──────────────────┬──────────────────────────────┘

┌──────────────────▼──────────────────────────────┐
│ HTTP Response                                    │
└──────────────────────────────────────────────────┘

Built-in Middleware Quick Reference

Middleware
Method
When to Use
Position

Developer Exception Page

UseDeveloperExceptionPage()

Development only

First

Exception Handler

UseExceptionHandler("/error")

Production

First

HSTS

UseHsts()

Production HTTPS

After exception

HTTPS Redirection

UseHttpsRedirection()

HTTP → HTTPS

Early

Static Files

UseStaticFiles()

Serve wwwroot files

Before routing

Routing

UseRouting()

Enable routing

Before auth

CORS

UseCors()

Cross-origin requests

After routing

Authentication

UseAuthentication()

Identify user

Before authorization

Authorization

UseAuthorization()

Check permissions

After authentication

Session

UseSession()

Enable sessions

After routing

Response Compression

UseResponseCompression()

Compress responses

Early

Request Localization

UseRequestLocalization()

i18n/l10n

After routing

Response Caching

UseResponseCaching()

Cache responses

Before endpoints

Common Middleware Mistakes

❌ Wrong
✅ Correct
Issue

UseAuthorization() before UseAuthentication()

UseAuthentication() then UseAuthorization()

Can't authorize without identity

UseRouting() after UseAuthorization()

UseRouting() before UseAuthorization()

Routing must happen first

UseCors() after UseAuthorization()

UseCors() before UseAuthorization()

CORS needs to be early

UseStaticFiles() after UseRouting()

UseStaticFiles() before UseRouting()

Skip routing for static files

Custom middleware after endpoints

Custom middleware before endpoints

Can't intercept endpoint execution

Minimal Program.cs Template

Request/Response Flow

Key Principles

  1. Exception handling first - Catch all errors

  2. Security early - HTTPS, CORS, Auth

  3. Static files before routing - Performance

  4. Auth before authorization - Identity first

  5. Custom middleware before endpoints - Intercept requests

  6. Endpoints last - Process the request


Card 2: Service Lifetimes Quick Reference

Service Lifetime Types

Registration Methods

Visual Lifetime Comparison

When to Use Which

Service Type
Use Transient
Use Scoped
Use Singleton

DbContext

❌ Never

✅ Always

❌ Never

Repository

❌ Rarely

✅ Usually

❌ Rarely

Email Service

✅ Yes

⚠️ Maybe

❌ No

Cache Service

❌ No

❌ No

✅ Yes

Configuration

❌ No

❌ No

✅ Yes

Logger

❌ No

❌ No

✅ Yes

HTTP Client

❌ No

❌ No

✅ Yes*

Validators

✅ Yes

⚠️ Maybe

❌ No

*Use IHttpClientFactory instead

Common Service Patterns

Dependency Rules (Captive Dependencies)

Captive Dependency Example:

Decision Tree

Common Registrations

Tips

  1. Default to Scoped for most services

  2. Use Transient for lightweight, stateless services

  3. Use Singleton only if thread-safe and stateless

  4. Never inject Scoped into Singleton (captive dependency)

  5. DbContext is always Scoped

  6. Configuration is always Singleton


Card 3: HTTP Methods & Status Codes

HTTP Methods (Verbs)

Method
Purpose
Body
Idempotent
Safe
Cacheable

GET

Retrieve resource

No

✅ Yes

✅ Yes

✅ Yes

POST

Create resource

✅ Yes

❌ No

❌ No

⚠️ Rarely

PUT

Replace resource

✅ Yes

✅ Yes

❌ No

❌ No

PATCH

Update partial

✅ Yes

❌ No

❌ No

❌ No

DELETE

Remove resource

No*

✅ Yes

❌ No

❌ No

HEAD

Get headers only

No

✅ Yes

✅ Yes

✅ Yes

OPTIONS

Get allowed methods

No

✅ Yes

✅ Yes

❌ No

*Can have body but rarely used

HTTP Status Codes

2xx Success

Code
Name
When to Use
Action Result

200

OK

Successful GET, PUT, PATCH

Ok(data)

201

Created

Resource created (POST)

Created(uri, data)

202

Accepted

Async processing started

Accepted()

204

No Content

Successful DELETE, PUT

NoContent()

3xx Redirection

Code
Name
When to Use
Action Result

301

Moved Permanently

Resource moved forever

RedirectPermanent(url)

302

Found

Temporary redirect

Redirect(url)

304

Not Modified

Cached version valid

-

4xx Client Errors

Code
Name
When to Use
Action Result

400

Bad Request

Invalid input/validation failed

BadRequest(error)

401

Unauthorized

Authentication required

Unauthorized()

403

Forbidden

Authenticated but not authorized

Forbid()

404

Not Found

Resource doesn't exist

NotFound(message)

405

Method Not Allowed

Wrong HTTP method

-

409

Conflict

Resource conflict (duplicate)

Conflict(error)

415

Unsupported Media Type

Wrong Content-Type

-

422

Unprocessable Entity

Validation failed (semantic)

-

429

Too Many Requests

Rate limit exceeded

StatusCode(429)

5xx Server Errors

Code
Name
When to Use
Action Result

500

Internal Server Error

Unhandled exception

StatusCode(500, error)

501

Not Implemented

Feature not implemented

StatusCode(501)

502

Bad Gateway

Invalid proxy response

-

503

Service Unavailable

Service temporarily down

StatusCode(503)

504

Gateway Timeout

Proxy timeout

-

RESTful API Patterns

Complete CRUD Example

Status Code Decision Tree

Common Mistakes

❌ Wrong
✅ Correct

return Ok("Not found")

return NotFound()

return Ok(error) for errors

return BadRequest(error)

POST returns 200

POST returns 201

DELETE returns 200 with data

DELETE returns 204

404 with body describing error

404 with simple message

Always returning 200

Use appropriate status codes

Quick Tips

  • GET = Retrieve (200 or 404)

  • POST = Create (201 + Location header)

  • PUT = Replace entire resource (204 or 200)

  • PATCH = Update partial (204 or 200)

  • DELETE = Remove (204)

  • 4xx = Client's fault

  • 5xx = Server's fault


Card 4: EF Core Quick Reference

DbContext Essentials

Registration & Connection String

CRUD Operations

Common Query Patterns

Migrations Commands

Relationships

Performance Tips

Common Patterns


Card 5: Validation Attributes

Built-in Validation Attributes

Complete Validation Attributes Reference

Attribute
Purpose
Example

[Required]

Field must have value

[Required]

[StringLength]

String length limits

[StringLength(100, MinimumLength = 2)]

[MinLength]

Minimum length

[MinLength(5)]

[MaxLength]

Maximum length

[MaxLength(100)]

[Range]

Numeric range

[Range(1, 100)]

[EmailAddress]

Valid email

[EmailAddress]

[Phone]

Valid phone

[Phone]

[Url]

Valid URL

[Url]

[CreditCard]

Valid credit card

[CreditCard]

[Compare]

Match another property

[Compare("Password")]

[RegularExpression]

Match regex pattern

[RegularExpression(@"^\d{5}$")]

[DataType]

Specify data type

[DataType(DataType.Date)]

[Display]

Display name

[Display(Name = "Full Name")]

Common Regex Patterns

Custom Validation Attribute

FluentValidation Quick Start

Model State Handling

Validation Error Response


Card 6: Authentication & Authorization

Authentication vs Authorization

JWT Authentication Setup

Authorization Attributes

Role-Based Authorization

Claims-Based Authorization

Policy-Based Authorization ⭐

Custom Authorization Requirement

Common Auth Patterns

Quick Decision Tree


These 6 quick reference cards cover the most essential ASP.NET Core concepts for quick desk-side reference!

Last updated