11. Common Interfaces & Namespaces
ASP.NET Core Common Interfaces, Classes & Namespaces - Complete Reference
Quick Reference Guide + Technical Documentation
📋 Table of Contents
Part 1: Core Types Quick Reference (Organized by Category)
Core HTTP Types (HttpContext, HttpRequest, HttpResponse)
Middleware Types (IMiddleware, RequestDelegate, IApplicationBuilder)
Dependency Injection (IServiceCollection, IServiceProvider, Lifetimes)
Configuration (IConfiguration, IOptions, IOptionsSnapshot, IOptionsMonitor)
Database (DbContext, DbSet, ModelBuilder)
Controllers & Routing (ControllerBase, IActionResult, RouteData)
Authentication & Authorization (ClaimsPrincipal, UserManager, SignInManager)
Logging (ILogger, LogLevel, ILoggerFactory)
Filters (IActionFilter, IExceptionFilter, IAuthorizationFilter)
Hosting & Application (WebApplication, WebApplicationBuilder, IWebHostEnvironment)
Part 2: Namespace Reference
Essential Namespaces by Category
Part 3: Common Attributes Reference
Attributes by Category (Routing, Validation, API, Authorization, Filters)
Part 4: Quick Lookup Tables
HTTP Status Codes - Complete Reference
Content Types - Common MIME Types
Extension Methods - Commonly Used Extensions
Common Patterns - Code Snippets for Frequent Tasks
PART 1: CORE TYPES QUICK REFERENCE
1. Core HTTP Types
HttpContext ⭐⭐⭐
Purpose: Encapsulates all HTTP request/response information for a single HTTP request
Namespace: Microsoft.AspNetCore.Http
Declaration:
Key Members:
Request
HttpRequest
Incoming HTTP request
context.Request.Path
Response
HttpResponse
Outgoing HTTP response
context.Response.StatusCode = 200
User
ClaimsPrincipal
Authenticated user
context.User.Identity.Name
Items
IDictionary<object, object>
Request-scoped data storage
context.Items["Key"] = value
RequestServices
IServiceProvider
Access DI services
context.RequestServices.GetService<T>()
Connection
ConnectionInfo
Connection details
context.Connection.RemoteIpAddress
RequestAborted
CancellationToken
Request cancellation
await Task.Delay(1000, context.RequestAborted)
Session
ISession
Session data
context.Session.SetString("key", "value")
TraceIdentifier
string
Unique request ID
context.TraceIdentifier
Features
IFeatureCollection
Request features
context.Features.Get<IHttpRequestFeature>()
Common Usage Patterns:
1. Access Request Information:
2. Modify Response:
3. Access User Information:
4. Store Request-Scoped Data:
5. Resolve Services:
HttpRequest ⭐⭐⭐
Purpose: Represents incoming HTTP request
Namespace: Microsoft.AspNetCore.Http
Key Members:
Method
string
HTTP verb (GET, POST, etc.)
request.Method == "GET"
Scheme
string
http or https
request.Scheme
Host
HostString
Domain and port
request.Host.Value
Path
PathString
URL path
request.Path.Value
PathBase
PathString
Application base path
request.PathBase
QueryString
QueryString
Raw query string
request.QueryString.Value
Query
IQueryCollection
Parsed query parameters
request.Query["page"]
Headers
IHeaderDictionary
HTTP headers
request.Headers["Authorization"]
Cookies
IRequestCookieCollection
Request cookies
request.Cookies["session"]
ContentType
string
Content-Type header
request.ContentType
ContentLength
long?
Request body size
request.ContentLength
Body
Stream
Request body stream
await request.Body.ReadAsync(buffer)
Form
IFormCollection
Form data (POST)
request.Form["username"]
HasFormContentType
bool
Is form data
request.HasFormContentType
IsHttps
bool
Is HTTPS request
request.IsHttps
Protocol
string
HTTP protocol version
request.Protocol
RouteValues
RouteValueDictionary
Route parameters
request.RouteValues["id"]
Complete Example:
Reading Request Body:
HttpResponse ⭐⭐⭐
Purpose: Represents outgoing HTTP response
Namespace: Microsoft.AspNetCore.Http
Key Members:
StatusCode
int
HTTP status code
response.StatusCode = 200
ContentType
string
Content-Type header
response.ContentType = "application/json"
ContentLength
long?
Response body size
response.ContentLength = 1024
Headers
IHeaderDictionary
HTTP headers
response.Headers.Add("X-Custom", "Value")
Cookies
IResponseCookies
Response cookies
response.Cookies.Append("session", "value")
Body
Stream
Response body stream
await response.Body.WriteAsync(bytes)
BodyWriter
PipeWriter
High-performance writing
response.BodyWriter
HasStarted
bool
Response started
if (!response.HasStarted)
OnStarting
event
Called before response
response.OnStarting(callback)
OnCompleted
event
Called after response
response.OnCompleted(callback)
Common Patterns:
1. Setting Status and Content Type:
2. Writing JSON:
3. Writing Text:
4. Setting Headers:
5. Setting Cookies:
6. Redirecting:
7. Streaming Large Response:
IHeaderDictionary ⭐⭐
Purpose: Collection of HTTP headers
Namespace: Microsoft.AspNetCore.Http
Declaration:
Common Operations:
IQueryCollection ⭐⭐
Purpose: Collection of query string parameters
Namespace: Microsoft.AspNetCore.Http
Usage:
IFormCollection ⭐⭐
Purpose: Collection of form data
Namespace: Microsoft.AspNetCore.Http
Usage:
2. Middleware Types
IMiddleware ⭐⭐
Purpose: Factory-based middleware creation (supports scoped/transient lifetimes)
Namespace: Microsoft.AspNetCore.Http
Declaration:
When to Use:
✅ Need scoped services (DbContext, etc.)
✅ Need transient lifetime
✅ Factory pattern for middleware
❌ Performance is critical (slight overhead)
Complete Example:
RequestDelegate
Purpose: Represents the next middleware in the pipeline
Namespace: Microsoft.AspNetCore.Http
Declaration:
Usage in Middleware:
Key Points:
Always injected by framework in constructor
Calling
await _next(context)continues pipelineNot calling
_nextshort-circuits the pipeline
IApplicationBuilder ⭐⭐⭐
Purpose: Configure the HTTP request pipeline
Namespace: Microsoft.AspNetCore.Builder
Key Members:
Use()
Add middleware (can call next)
app.Use(async (ctx, next) => await next())
Run()
Terminal middleware (no next)
app.Run(async ctx => await ctx.Response.WriteAsync("Hi"))
Map()
Branch pipeline by path
app.Map("/api", apiApp => {...})
MapWhen()
Branch by condition
app.MapWhen(ctx => ctx.Request.IsHttps, ...)
UseWhen()
Conditional middleware (rejoins)
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), ...)
ApplicationServices
Service provider
app.ApplicationServices
ServerFeatures
Server capabilities
app.ServerFeatures
Common Patterns:
Extension Method Pattern:
3. Dependency Injection
IServiceCollection ⭐⭐⭐
Purpose: Register services for dependency injection
Namespace: Microsoft.Extensions.DependencyInjection
Declaration:
Key Methods:
AddTransient<TService, TImplementation>()
Transient
New instance every time
services.AddTransient<IEmailService, EmailService>()
AddScoped<TService, TImplementation>()
Scoped
One per request
services.AddScoped<IUserService, UserService>()
AddSingleton<TService, TImplementation>()
Singleton
One for app lifetime
services.AddSingleton<ICacheService, CacheService>()
AddTransient<TService>(factory)
Transient
Factory method
services.AddTransient<IService>(sp => new Service())
AddScoped<TService>(factory)
Scoped
Factory method
services.AddScoped<IService>(sp => new Service())
AddSingleton<TService>(factory)
Singleton
Factory method
services.AddSingleton<IService>(sp => new Service())
AddSingleton<TService>(instance)
Singleton
Specific instance
services.AddSingleton<IConfig>(config)
Service Lifetime Comparison:
Transient
Every request
Lightweight, stateless services
Email sender, HTTP client wrapper
Scoped
Once per HTTP request
Database contexts, unit of work
DbContext, request-specific services
Singleton
Once for app lifetime
Shared state, caching, configuration
Configuration, cache, logging factory
Visual Diagram:
Registration Examples:
1. Basic Registration:
2. Factory Method:
3. With Options:
4. Multiple Implementations:
5. Keyed Services (.NET 8.0+):
IServiceProvider ⭐⭐
Purpose: Resolve registered services
Namespace: System
Key Methods:
GetService<T>()
Get service
Returns null
GetRequiredService<T>()
Get service
Throws exception
GetServices<T>()
Get all implementations
Returns empty
GetKeyedService<T>(key)
Get keyed service (.NET 8+)
Returns null
GetRequiredKeyedService<T>(key)
Get keyed service (.NET 8+)
Throws exception
Usage Examples:
ServiceLifetime Enum
Purpose: Defines service lifetime in DI container
Namespace: Microsoft.Extensions.DependencyInjection
Values:
When to Use Which:
Database context (EF Core)
Scoped
Per-request, manages transaction scope
HTTP client
Singleton/Transient
Reuse connections (use IHttpClientFactory)
Logging
Singleton
Shared logger factory
Caching service
Singleton
Shared cache across all requests
Email service
Transient
Stateless, lightweight
Unit of Work
Scoped
Per-request transaction
Configuration
Singleton
Same for entire app
User service (with DbContext)
Scoped
Depends on scoped DbContext
Decision Tree:
4. Configuration
IConfiguration ⭐⭐⭐
Purpose: Read application configuration
Namespace: Microsoft.Extensions.Configuration
Key Members:
[key]
Get value by key
config["AppName"]
GetSection()
Get configuration section
config.GetSection("ConnectionStrings")
GetChildren()
Get child sections
config.GetChildren()
Exists()
Check if key exists
config.GetSection("Key").Exists()
GetValue<T>()
Get typed value
config.GetValue<int>("Port")
Get<T>()
Bind to object
config.Get<AppSettings>()
Bind()
Bind to existing object
config.Bind(settings)
Reading Configuration:
appsettings.json:
Method 1: Direct Access (Simple Values)
Method 2: GetSection (Nested Values)
Method 3: Strongly-Typed (Best Practice)
Method 4: Arrays
IOptions ⭐⭐
Purpose: Strongly-typed configuration (singleton pattern)
Namespace: Microsoft.Extensions.Options
Declaration:
When to Use:
✅ Configuration doesn't change during runtime
✅ Singleton services
❌ Need to reload configuration
Setup:
IOptionsSnapshot ⭐⭐
Purpose: Scoped configuration reload (per-request)
Namespace: Microsoft.Extensions.Options
When to Use:
✅ Need configuration reload per request
✅ Scoped services
❌ Singleton services (can't inject scoped into singleton)
Usage:
IOptionsMonitor ⭐⭐
Purpose: Live configuration reload (singleton with change notifications)
Namespace: Microsoft.Extensions.Options
Declaration:
When to Use:
✅ Need live reload in singleton services
✅ React to configuration changes
✅ Named options
Usage:
IOptions Comparison Table
Feature
IOptions
IOptionsSnapshot
IOptionsMonitor
Lifetime
Singleton
Scoped
Singleton
Reload
No
Per request
Live
Change notification
No
No
Yes
Named options
No
Yes
Yes
Performance
Fastest
Medium
Slower
Use in singleton
Yes
❌ No
Yes
Use in scoped
Yes
Yes
Yes
Best for
Static config
Per-request reload
Live config changes
When to Use:
5. Database (Entity Framework Core)
DbContext ⭐⭐⭐
Purpose: Database session and unit of work
Namespace: Microsoft.EntityFrameworkCore
Key Members:
Database
Database operations
context.Database.EnsureCreated()
SaveChanges()
Save changes synchronously
context.SaveChanges()
SaveChangesAsync()
Save changes asynchronously
await context.SaveChangesAsync()
Entry()
Get entity entry
context.Entry(user).State
Set<T>()
Get DbSet
context.Set<User>()
Add()
Track entity for insert
context.Add(user)
Update()
Track entity for update
context.Update(user)
Remove()
Track entity for delete
context.Remove(user)
ChangeTracker
Track entity states
context.ChangeTracker.Entries()
Complete Example:
DbSet ⭐⭐⭐
Purpose: Collection of entities for a type
Namespace: Microsoft.EntityFrameworkCore
Key Methods:
Add()
Add new entity
context.Users.Add(user)
AddRange()
Add multiple entities
context.Users.AddRange(users)
Update()
Update entity
context.Users.Update(user)
UpdateRange()
Update multiple
context.Users.UpdateRange(users)
Remove()
Delete entity
context.Users.Remove(user)
RemoveRange()
Delete multiple
context.Users.RemoveRange(users)
Find()
Find by primary key
context.Users.Find(5)
FindAsync()
Find by PK async
await context.Users.FindAsync(5)
AsNoTracking()
Query without tracking
context.Users.AsNoTracking()
CRUD Operations:
Querying Patterns:
ModelBuilder ⭐⭐
Purpose: Configure entity models using Fluent API
Namespace: Microsoft.EntityFrameworkCore
Common Configurations:
6. Controllers & Routing
ControllerBase ⭐⭐⭐
Purpose: Base class for API controllers (no view support)
Namespace: Microsoft.AspNetCore.Mvc
Key Properties:
HttpContext
HttpContext
Current HTTP context
Request
HttpRequest
Current HTTP request
Response
HttpResponse
Current HTTP response
User
ClaimsPrincipal
Current user
ModelState
ModelStateDictionary
Model validation state
Url
IUrlHelper
Generate URLs
RouteData
RouteData
Current route data
Result Helper Methods:
Ok()
200
Success
Ok(data)
Created()
201
Resource created
Created(uri, data)
CreatedAtAction()
201
Created with action route
CreatedAtAction(nameof(Get), new { id }, data)
NoContent()
204
Success, no content
NoContent()
BadRequest()
400
Client error
BadRequest(error)
Unauthorized()
401
Not authenticated
Unauthorized()
Forbid()
403
Not authorized
Forbid()
NotFound()
404
Resource not found
NotFound()
Conflict()
409
Conflict
Conflict(error)
UnprocessableEntity()
422
Validation error
UnprocessableEntity(ModelState)
StatusCode()
Custom
Custom status
StatusCode(500, error)
Complete Controller Example:
IActionResult ⭐⭐⭐
Purpose: Represents the result of an action method
Namespace: Microsoft.AspNetCore.Mvc
Common Implementations:
OkResult
200
Success, no content
OkObjectResult
200
Success with content
CreatedResult
201
Resource created
CreatedAtActionResult
201
Created with route
NoContentResult
204
Success, no content
BadRequestResult
400
Client error
BadRequestObjectResult
400
Client error with details
UnauthorizedResult
401
Not authenticated
ForbidResult
403
Not authorized
NotFoundResult
404
Resource not found
NotFoundObjectResult
404
Not found with message
ConflictResult
409
Conflict
UnprocessableEntityResult
422
Validation failed
StatusCodeResult
Custom
Custom status code
JsonResult
200
JSON response
FileResult
200
File download
RedirectResult
302
Redirect
Usage Patterns:
ActionResult (.NET Core 2.1+)
Purpose: Strongly-typed action result
Benefits:
✅ IntelliSense support
✅ Return T directly or IActionResult
✅ Automatic serialization
✅ API documentation generation
Example:
RouteData ⭐
Purpose: Contains route values for current request
Namespace: Microsoft.AspNetCore.Routing
Usage:
7. Authentication & Authorization
ClaimsPrincipal ⭐⭐
Purpose: Represents the current user
Namespace: System.Security.Claims
Key Members:
Identity
Primary identity
User.Identity.Name
Identities
All identities
User.Identities
Claims
All claims
User.Claims
FindFirst()
Get first claim
User.FindFirst(ClaimTypes.NameIdentifier)
FindAll()
Get all claims of type
User.FindAll("role")
HasClaim()
Check claim exists
User.HasClaim("admin", "true")
IsInRole()
Check role
User.IsInRole("Admin")
Common Usage:
ClaimsIdentity ⭐
Purpose: Represents a single identity
Namespace: System.Security.Claims
Usage:
Claim ⭐
Purpose: Represents a single claim (key-value pair)
Namespace: System.Security.Claims
Common Claim Types:
Creating Claims:
UserManager ⭐⭐
Purpose: Manages users in ASP.NET Core Identity
Namespace: Microsoft.AspNetCore.Identity
Key Methods:
CreateAsync()
Create new user
UpdateAsync()
Update user
DeleteAsync()
Delete user
FindByIdAsync()
Find by ID
FindByEmailAsync()
Find by email
FindByNameAsync()
Find by username
AddToRoleAsync()
Add user to role
RemoveFromRoleAsync()
Remove from role
GetRolesAsync()
Get user roles
IsInRoleAsync()
Check if in role
AddClaimAsync()
Add claim to user
RemoveClaimAsync()
Remove claim
GetClaimsAsync()
Get user claims
Example:
SignInManager ⭐⭐
Purpose: Manages user sign-in
Namespace: Microsoft.AspNetCore.Identity
Key Methods:
SignInAsync()
Sign in user
SignOutAsync()
Sign out user
PasswordSignInAsync()
Sign in with password
IsSignedIn()
Check if signed in
GetExternalAuthenticationSchemesAsync()
Get external providers
Example:
8. Logging
ILogger ⭐⭐⭐
Purpose: Log messages with structured logging
Namespace: Microsoft.Extensions.Logging
Key Methods:
LogTrace()
Trace
Detailed diagnostic info
LogDebug()
Debug
Debugging during development
LogInformation()
Information
General flow of application
LogWarning()
Warning
Unexpected but handled events
LogError()
Error
Error that stopped operation
LogCritical()
Critical
Critical failure
Log()
Custom
Custom log level
Usage:
Structured Logging:
Log Scopes:
LogLevel Enum
Purpose: Defines log severity
Namespace: Microsoft.Extensions.Logging
When to Use:
Trace
Very detailed diagnostic
Variable values, method entry/exit
Debug
Debugging information
Query details, cache hits/misses
Information
General application flow
User logged in, order placed
Warning
Unexpected but handled
Missing optional config, deprecated API
Error
Error that stopped current operation
Database error, file not found
Critical
System-wide failure
Database down, out of memory
Configuration (appsettings.json):
ILoggerFactory ⭐
Purpose: Create logger instances
Namespace: Microsoft.Extensions.Logging
Usage:
9. Filters
IActionFilter ⭐⭐
Purpose: Execute code before/after action execution
Namespace: Microsoft.AspNetCore.Mvc.Filters
Declaration:
Async Version:
Example:
IExceptionFilter ⭐⭐
Purpose: Handle exceptions from actions
Namespace: Microsoft.AspNetCore.Mvc.Filters
Declaration:
Example:
IAuthorizationFilter ⭐⭐
Purpose: Perform authorization
Namespace: Microsoft.AspNetCore.Mvc.Filters
Declaration:
Example:
Filter Pipeline Order
10. Hosting & Application
WebApplication ⭐⭐⭐
Purpose: Represents configured application in minimal hosting model (.NET 6+)
Namespace: Microsoft.AspNetCore.Builder
Key Members:
Services
Service provider
app.Services.GetService<T>()
Configuration
Configuration
app.Configuration["Key"]
Environment
Host environment
app.Environment.IsDevelopment()
Lifetime
Application lifetime
app.Lifetime.ApplicationStopping
Urls
Server URLs
app.Urls
Logger
Logger factory
app.Logger
Run()
Start application
app.Run()
RunAsync()
Start async
await app.RunAsync()
StartAsync()
Start without blocking
await app.StartAsync()
StopAsync()
Stop application
await app.StopAsync()
Both IApplicationBuilder and IEndpointRouteBuilder:
Example:
WebApplicationBuilder ⭐⭐⭐
Purpose: Builder for WebApplication
Namespace: Microsoft.AspNetCore.Builder
Key Members:
Services
Service collection
builder.Services.AddScoped<T>()
Configuration
Configuration builder
builder.Configuration.GetSection("Key")
Environment
Host environment
builder.Environment.EnvironmentName
Host
Host builder
builder.Host.ConfigureServices()
WebHost
Web host builder
builder.WebHost.UseUrls()
Logging
Logging builder
builder.Logging.AddConsole()
Build()
Build application
var app = builder.Build()
Example:
IWebHostEnvironment ⭐⭐
Purpose: Provides information about web hosting environment
Namespace: Microsoft.AspNetCore.Hosting
Key Members:
EnvironmentName
string
Environment name (Development, Staging, Production)
ApplicationName
string
Application name
ContentRootPath
string
Content root directory path
WebRootPath
string
Web root directory path (wwwroot)
IsDevelopment()
bool
Is Development environment
IsStaging()
bool
Is Staging environment
IsProduction()
bool
Is Production environment
IsEnvironment(name)
bool
Check specific environment
Usage:
PART 2: NAMESPACE REFERENCE
11. Essential Namespaces by Category
Core HTTP
Key Types:
HttpContext
HttpRequest
HttpResponse
IHeaderDictionary
IQueryCollection
IFormCollection
ISession
CookieOptions
StatusCodes
When to Use: Working with HTTP requests/responses, middleware
HTTP Features
Key Types:
IHttpRequestFeature
IHttpResponseFeature
IHttpConnectionFeature
IHttpRequestLifetimeFeature
When to Use: Low-level HTTP features, advanced scenarios
Middleware & Pipeline
Key Types:
IApplicationBuilder
WebApplication
WebApplicationBuilder
EndpointRouteBuilderExtensions
When to Use: Configuring middleware pipeline, application setup
MVC / Controllers
Key Types:
ControllerBase
Controller (with view support)
IActionResult
ActionResult
JsonResult
ObjectResult
StatusCodeResult
FileResult
RedirectResult
When to Use: Creating API controllers, MVC controllers
MVC Filters
Key Types:
IActionFilter
IAsyncActionFilter
IExceptionFilter
IAuthorizationFilter
IResourceFilter
IResultFilter
FilterAttribute
When to Use: Creating filters for cross-cutting concerns
Model Binding
Key Types:
ModelStateDictionary
IModelBinder
BindingSource
ModelBinderAttribute
When to Use: Custom model binding, validation
Routing
Key Types:
IRouter
RouteData
RouteValueDictionary
LinkGenerator
EndpointDataSource
When to Use: Custom routing, URL generation
Dependency Injection
Key Types:
IServiceCollection
IServiceProvider
ServiceDescriptor
ServiceLifetime
ActivatorUtilities
When to Use: Registering services, service resolution
Configuration
Key Types:
IConfiguration
IConfigurationBuilder
IConfigurationSection
ConfigurationManager
When to Use: Reading configuration
Options Pattern
Key Types:
IOptions
IOptionsSnapshot
IOptionsMonitor
IConfigureOptions
OptionsBuilder
When to Use: Strongly-typed configuration
Logging
Key Types:
ILogger
ILoggerFactory
LogLevel
ILoggingBuilder
When to Use: Logging throughout application
Hosting
Key Types:
IWebHostEnvironment
IHostEnvironment
IHostBuilder
IHost
IHostApplicationLifetime
When to Use: Application startup, environment checks
Entity Framework Core
Key Types:
DbContext
DbSet
ModelBuilder
DbContextOptions
ChangeTracker
Database
When to Use: Database access with EF Core
Authentication
Key Types:
AuthenticationOptions
JwtBearerOptions
CookieAuthenticationOptions
AuthenticationScheme
When to Use: Configuring authentication
Authorization
Key Types:
AuthorizeAttribute
AllowAnonymousAttribute
IAuthorizationService
AuthorizationPolicy
IAuthorizationRequirement
When to Use: Authorization policies, requirements
Identity
Key Types:
UserManager
SignInManager
RoleManager
IdentityUser
IdentityRole
IdentityResult
When to Use: User management with Identity
Claims
Key Types:
ClaimsPrincipal
ClaimsIdentity
Claim
ClaimTypes
When to Use: Working with user claims
PART 3: COMMON ATTRIBUTES REFERENCE
12. Attributes by Category
Routing Attributes
[Route]
Define route template
[Route("api/[controller]")]
[HttpGet]
HTTP GET method
[HttpGet("{id}")]
[HttpPost]
HTTP POST method
[HttpPost]
[HttpPut]
HTTP PUT method
[HttpPut("{id}")]
[HttpDelete]
HTTP DELETE method
[HttpDelete("{id}")]
[HttpPatch]
HTTP PATCH method
[HttpPatch("{id}")]
[HttpHead]
HTTP HEAD method
[HttpHead]
[HttpOptions]
HTTP OPTIONS method
[HttpOptions]
Examples:
Model Binding Attributes
[FromRoute]
Bind from route data
public IActionResult Get([FromRoute] int id)
[FromQuery]
Bind from query string
public IActionResult Get([FromQuery] string name)
[FromBody]
Bind from request body
public IActionResult Create([FromBody] User user)
[FromForm]
Bind from form data
public IActionResult Upload([FromForm] IFormFile file)
[FromHeader]
Bind from header
public IActionResult Get([FromHeader] string apiKey)
[FromServices]
Inject from DI
public IActionResult Get([FromServices] IUserService service)
Examples:
Validation Attributes
[Required]
Field is required
[Required] public string Name { get; set; }
[StringLength]
Max/min string length
[StringLength(100, MinimumLength = 3)]
[MinLength]
Minimum length
[MinLength(3)]
[MaxLength]
Maximum length
[MaxLength(100)]
[Range]
Numeric range
[Range(1, 100)]
[EmailAddress]
Valid email format
[EmailAddress]
[Phone]
Valid phone format
[Phone]
[Url]
Valid URL format
[Url]
[CreditCard]
Valid credit card
[CreditCard]
[RegularExpression]
Regex pattern
[RegularExpression(@"^\d{3}-\d{2}-\d{4}$")]
[Compare]
Compare two properties
[Compare("Password")]
Example DTO:
API Attributes
[ApiController]
Enable API behaviors
[ApiController]
[Produces]
Response content type
[Produces("application/json")]
[Consumes]
Request content type
[Consumes("application/json")]
[ProducesResponseType]
Document response types
[ProducesResponseType(200, Type = typeof(User))]
Examples:
Authorization Attributes
[Authorize]
Require authentication
[Authorize]
[Authorize(Roles)]
Require specific role
[Authorize(Roles = "Admin")]
[Authorize(Policy)]
Require policy
[Authorize(Policy = "MinAge18")]
[AllowAnonymous]
Allow anonymous access
[AllowAnonymous]
Examples:
Filter Attributes
[ServiceFilter]
Use filter from DI
[ServiceFilter(typeof(MyFilter))]
[TypeFilter]
Use filter (creates instance)
[TypeFilter(typeof(MyFilter))]
[ValidateAntiForgeryToken]
Validate anti-forgery token
[ValidateAntiForgeryToken]
[IgnoreAntiforgeryToken]
Ignore anti-forgery
[IgnoreAntiforgeryToken]
Examples:
PART 4: QUICK LOOKUP TABLES
13. HTTP Status Codes - Complete Reference
Success (2xx)
200
OK
Successful GET, PUT, PATCH
201
Created
Successful POST (resource created)
202
Accepted
Request accepted (async processing)
204
No Content
Successful DELETE, PUT (no body)
206
Partial Content
Partial GET (range request)
Redirection (3xx)
301
Moved Permanently
Resource permanently moved
302
Found
Temporary redirect
304
Not Modified
Cached resource still valid
307
Temporary Redirect
Temporary redirect (same method)
308
Permanent Redirect
Permanent redirect (same method)
Client Errors (4xx)
400
Bad Request
Invalid request
Malformed JSON
401
Unauthorized
Not authenticated
Missing/invalid token
403
Forbidden
Not authorized
Insufficient permissions
404
Not Found
Resource not found
User doesn't exist
405
Method Not Allowed
HTTP method not supported
POST on read-only endpoint
409
Conflict
Conflict with current state
Duplicate email
415
Unsupported Media Type
Wrong Content-Type
Sent XML, expects JSON
422
Unprocessable Entity
Validation failed
Email format invalid
429
Too Many Requests
Rate limit exceeded
Too many API calls
Server Errors (5xx)
500
Internal Server Error
Unexpected server error
Unhandled exception
501
Not Implemented
Not implemented
Feature not ready
502
Bad Gateway
Invalid response from upstream
Proxy error
503
Service Unavailable
Service temporarily unavailable
Database down
504
Gateway Timeout
Upstream timeout
Long-running operation
Common Patterns:
14. Content Types - Common MIME Types
Application
application/json
.json
JSON data (APIs)
application/xml
.xml
XML data
application/pdf
PDF documents
application/zip
.zip
ZIP archives
application/x-www-form-urlencoded
-
Form data (POST)
application/octet-stream
-
Binary data
Text
text/plain
.txt
Plain text
text/html
.html
HTML documents
text/css
.css
CSS files
text/javascript
.js
JavaScript files
text/csv
.csv
CSV data
Image
image/jpeg
.jpg, .jpeg
JPEG images
image/png
.png
PNG images
image/gif
.gif
GIF images
image/svg+xml
.svg
SVG images
image/webp
.webp
WebP images
Audio/Video
audio/mpeg
.mp3
MP3 audio
audio/wav
.wav
WAV audio
video/mp4
.mp4
MP4 video
video/webm
.webm
WebM video
Usage:
15. Extension Methods - Commonly Used
IServiceCollection Extensions
IApplicationBuilder Extensions
IEndpointRouteBuilder Extensions
16. Common Patterns - Code Snippets
Pattern 1: Async CRUD Controller
Pattern 2: Repository Pattern
Pattern 3: Result Pattern
Pattern 4: API Response Wrapper
Pattern 5: Unit of Work
Summary: Quick Reference Checklist
When building ASP.NET Core applications:
Core Types to Remember:
Common Patterns:
Essential Namespaces:
Key Attributes:
This completes the Common Interfaces, Classes & Namespaces Reference guide - your comprehensive desk reference for ASP.NET Core development!
Last updated