Web APIs are the backbone of modern applications, but they are also prime targets for Denial-of-Service (DoS) and Distributed Denial-of-Service (DDoS) attacks.
DoS Attack: A single attacker floods your server with excessive requests.
DDoS Attack: Multiple attackers (botnets) send massive traffic, overwhelming your system.
The result? Slow response times, unavailability, server crashes, and frustrated users.
In this article, weβll explore how to secure ASP.NET Core Web APIs against DoS/DDoS attacks using built-in middleware, best practices, and deployment strategies.
Common Symptoms of DoS/DDoS Attacks
Sudden spike in traffic from suspicious IPs.
High CPU and memory usage.
The API is returning 429 (Too Many Requests) or 503 (Service Unavailable) errors.
Database overload due to repeated queries.
Security Techniques for ASP.NET Core Web APIs
1. Request Rate Limiting (Throttling)
Rate limiting ensures that clients can only make a limited number of requests per second/minute.
In .NET 7+, you can use the Rate Limiting Middleware.
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
// Add Rate Limiter
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.Window = TimeSpan.FromSeconds(10); // Time window
opt.PermitLimit = 5; // Max requests per window
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
});
});
var app = builder.Build();
app.UseRateLimiter();
// API Endpoint
app.MapGet("/api/data", () => "Protected API")
.RequireRateLimiting("fixed");
app.Run();
This allows only five requests per 10 seconds per client.
If exceeded, the API returns a 429 Too Many Requests error.
2. IP Filtering and Blocking
You can block suspicious IPs directly at the middleware level.
app.Use(async (context, next) =>
{
var remoteIp = context.Connection.RemoteIpAddress;
var blockedIps = new List<string> { "192.168.1.100", "203.0.113.5" };
if (remoteIp != null && blockedIps.Contains(remoteIp.ToString()))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Forbidden");
return;
}
await next();
});
Helpful in blocking known malicious IPs.
3. Limit Request Body Size
Attackers may try to crash your API by sending massive payloads.
builder.Services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = 10 * 1024; // 10 KB
});
4. Response Caching
Reduce repeated database hits by caching responses.
builder.Services.AddResponseCaching();
app.UseResponseCaching();
app.MapGet("/api/time", () =>
{
return Results.Ok(DateTime.Now);
})
.WithMetadata(new ResponseCacheAttribute() { Duration = 30 });
5. Circuit Breakers with Polly
Prevent backend overload by using Polly.
builder.Services.AddHttpClient("SafeClient")
.AddTransientHttpErrorPolicy(p =>
p.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)));
6. Logging and Monitoring
Detect suspicious activity early with structured logging.
app.Use(async (context, next) =>
{
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Request from {IP}", context.Connection.RemoteIpAddress);
await next();
});
7. Deploying Reverse Proxy and WAF
Place your API behind Nginx, Apache, or Azure Front Door.
Use Cloudflare or AWS Shield for DDoS protection.
Apply Web Application Firewall (WAF) rules.
Real-World Security Architecture
[Client] β [Cloudflare / Azure DDoS Protection] β [Reverse Proxy (Nginx/Apache)]
β [ASP.NET Core Web API] β [Caching Layer (Redis/NCache)] β [Database]
Best Practices Checklist
β Enable Rate Limiting Middleware
β Block/Whitelist suspicious IPs
β Restrict MaxRequestBodySize
β Use Caching for frequent responses
β Implement Circuit Breakers to protect the backend
β Deploy WAF + Reverse Proxy
β Use Cloud Provider DDoS Protection
Conclusion
DoS and DDoS attacks pose serious threats to any ASP.NET Core Web API. By combining application-level protections (rate limiting, caching, IP blocking) with infrastructure-level solutions (reverse proxy, WAF, cloud DDoS protection), you can significantly reduce attack risks and improve resilience.
Remember: Security is not a one-time setup β itβs a continuous process of monitoring, testing, and improving .