ASP.NET Core Web API

API Key Authentication

1 Views Updated 5/4/2026

Rate Limiting & Throttling (.NET 7+)

Left unprotected, a malicious bot (or a poorly coded frontend loop) could blast your API with 5,000 requests per second, exhausting your database connections and crashing your server. Rate Limiting enforces maximum thresholds on how many times an endpoint can be hit.

1. Setting up Built-In Rate Limiting

Prior to .NET 7, developers relied on third-party libraries like 'AspNetCoreRateLimit'. Now, ASP.NET Core has an immensely powerful rate-limiter built directly into the kernel.

using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

// 1. Define the Policy
builder.Services.AddRateLimiter(options =>
{
    // If the limit is hit, return HTTP 429 Too Many Requests (Extremely important for REST compliance)
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

    // Define a Fixed Window Policy: Max 100 requests per 1-minute window
    options.AddFixedWindowLimiter("AntiBotPolicy", limiterOptions =>
    {
        limiterOptions.PermitLimit = 100;
        limiterOptions.Window = TimeSpan.FromMinutes(1);
        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        limiterOptions.QueueLimit = 0; // Don't queue requests; reject them instantly
    });
});

var app = builder.Build();

// 2. Add to pipeline (Must be BEFORE MapControllers)
app.UseRateLimiter(); 

2. Applying Limits to Specific Controllers

You generally do not want to rate limit the entire application globally. You want strict limits on expensive operations (like Generating a PDF) and loose limits on text reads.

[ApiController]
[Route("api/reports")]
// Attaches the "100 requests per minute" policy to everything in this controller
[EnableRateLimiting("AntiBotPolicy")] 
public class ReportingController : ControllerBase
{
    [HttpGet("heavy-pdf")]
    public IActionResult GenerateDeepAnalyticsPdf() 
    { ... }
    
    [HttpGet("status")]
    [DisableRateLimiting] // Exempts this specific method from the controller's limiter
    public IActionResult GetStatus() 
    { ... }
}

3. Global IP-Based Rate Limiting

A "Fixed Window Limiter" applies to the *entire server*. If the limit is 100, and 100 different users hit the endpoint once, the 101st user gets blocked. That is disastrous. We need to partition the limits so that it is 100 requests per IP Address.

options.AddPolicy("IpAddressPolicy", context =>
    RateLimitPartition.GetFixedWindowLimiter(
        partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
        factory: partition => new FixedWindowRateLimiterOptions
        {
            AutoReplenishment = true,
            PermitLimit = 10, // 10 requests total
            Window = TimeSpan.FromSeconds(10) // Per 10 seconds, Per IP Address!
        }));

4. Interview Mastery

Q: "In a heavily distributed environment where our API is deployed across 5 different servers via an Azure Load Balancer, does the built-in ASP.NET Core Rate Limiter still effectively stop DDoS attacks targeting a specific user?"

Architect Answer: "No, it becomes highly inaccurate. The built-in Rate Limiter operates strictly in the RAM (In-Memory) of the individual server processing the request. If a hacker sends 500 requests to guess a password, the Load Balancer might spread those requests evenly (100 per server). If our API Limit is set to 150 requests per minute, every single server will view the hacker as only hitting 100 requests, allowing them to completely bypass our global 150 limit! To solve distributed rate limiting, we must abandon the In-Memory limiter and implement a globally distributed counter using a Redis Cache backend, or better yet, shift the Rate Limiting logic entirely off our application onto an Azure API Management gateway firewall."

ASP.NET Core Web API
1. Fundamentals & HTTP
Introduction to ASP.NET Core Web API REST Principles and HTTP Methods Controllers & ControllerBase Routing (Attribute vs Conventional) Action Return Types (IActionResult)
2. Request Handling
Model Binding (FromQuery, FromBody, FromRoute) Dependency Injection (DI) Deep Dive App Settings & The Options Pattern
3. Data Access & Architecture
EF Core Setup in Web API DbContext & Migrations Repository & Unit of Work Pattern Asynchronous Programming (async/await)
4. Data Transfer & Validation
Data Transfer Objects (DTOs) & AutoMapper Model Validation (DataAnnotations) FluentValidation Integration
5. Advanced Concepts
Global Exception Handling Middleware Content Negotiation (JSON vs XML) Pagination & Filtering Advanced Searching & Sorting HATEOAS (Hypermedia) Implementation Output Caching & Response Caching
6. Security & Authorization
Cross-Origin Resource Sharing (CORS) JWT Authentication Setup Access Tokens & Refresh Tokens Workflow Role-Based & Policy-Based Authorization API Key Authentication Rate Limiting & Throttling
7. Documentation & Testing
Swagger & OpenAPI Configuration Customizing API Documentation Unit Testing Controllers (xUnit & Moq) Integration Testing (WebApplicationFactory)
8. Microservices & Deployment
Consuming External APIs (IHttpClientFactory) Health Checks & Diagnostics API Versioning Strategies Deploying APIs (Docker & Azure)