ASP.NET Core  

Preventing Denial of Service (DoS/DDoS) in ASP.NET Core Applications

Denial of Service (DoS) and Distributed Denial of Service (DDoS) attacks aim to make your application or API unavailable by overwhelming it with excessive requests, consuming resources like CPU, memory, bandwidth, or database connections. While complete prevention often requires infrastructure-level protection (firewalls, CDNs, reverse proxies), ASP.NET Core applications can still implement multiple layers of defense to mitigate the risks.

1. Understanding DoS/DDoS in Web Applications

  • DoS Attack: A single machine repeatedly sends requests to exhaust resources.

  • DDoS Attack: Multiple machines (botnets) flood the target server simultaneously, making it much harder to mitigate.

Common symptoms

  • High CPU and memory usage

  • Increased response times

  • Application crashes or timeouts

  • Database connection pool exhaustion

2. Mitigation Strategies in ASP.NET Core

2.1. Use Reverse Proxies, Firewalls, and CDNs

  • Deploy NGINX, HAProxy, or IIS Reverse Proxy in front of your ASP.NET Core app.

  • Use Web Application Firewalls (WAF) like Azure Front Door, Cloudflare, or AWS Shield for DDoS protection.

  • CDNs cache content closer to users, reducing load on the origin server.

2.2. Enable Rate Limiting and Throttling

ASP.NET Core 7+ has built-in Rate Limiting Middleware.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", c =>
    {
        c.PermitLimit = 100; // Max requests
        c.Window = TimeSpan.FromSeconds(10); // Per 10 seconds
        c.QueueLimit = 2;
        c.QueueProcessingOrder = System.Threading.RateLimiting.QueueProcessingOrder.OldestFirst;
    });
});

var app = builder.Build();

app.UseRateLimiter();

app.MapGet("/api/data", () => "Rate limited data")
   .RequireRateLimiting("fixed");

app.Run();

This prevents abusive clients from flooding endpoints.

2.3. Limit Request Body Size

Attackers may send extremely large payloads to consume server memory.

builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = 10 * 1024; // 10 KB
});

builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024; // 10 KB
});

2.4. Validate Input Early

Malicious requests with deeply nested JSON, large files, or invalid formats can exhaust processing power.

  • Use model validation in controllers.

  • Reject unexpected payloads quickly with custom middleware.

  • Use FluentValidation or data annotations.

2.5. Protect File Upload Endpoints

File uploads are a common DoS vector.

  • Restrict file size.

  • Restrict file type (MIME type + extension).

  • Scan uploaded files for malware.

  • Store files outside the web root.

if (file.Length > 5 * 1024 * 1024)
{
    return Results.BadRequest("File too large!");
}

2.6. Implement Caching

  • Use Response Caching Middleware to avoid recomputing responses.

  • Cache expensive database queries with IMemoryCache or Redis.

builder.Services.AddMemoryCache();

2.7. Asynchronous Programming

ASP.NET Core’s async model helps reduce thread pool starvation under load. Always use async/await with database and I/O operations.

2.8. Circuit Breakers and Timeouts

Prevent back-end systems from being overloaded by cascading failures:

  • Use Polly for retries, circuit breakers, and timeouts.

builder.Services.AddHttpClient("SafeClient")
    .AddPolicyHandler(Polly.Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(2)));

2.9. Connection Limits

Restrict simultaneous connections per IP to reduce resource exhaustion.
On Kestrel:

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxConcurrentConnections = 100;
    options.Limits.MaxConcurrentUpgradedConnections = 10;
});

2.10. Monitoring and Logging

  • Integrate Application Insights, Serilog, or ELK Stack for anomaly detection.

  • Set up alerts for unusual traffic spikes.

  • Monitor request headers, user agents, and IPs for suspicious patterns.

3. Infrastructure-Level Recommendations

ASP.NET Core alone cannot stop massive DDoS attacks. Combine app-level defenses with:

  • Load Balancers (Azure Load Balancer, AWS ELB).

  • DDoS Protection Services (Cloudflare, AWS Shield, Azure DDoS Protection).

  • Autoscaling on Kubernetes or cloud environments.

4. Best Practices Checklist

  • Use WAF/CDN for DDoS mitigation.

  • Apply ASP.NET Core Rate Limiting Middleware.

  • Limit request body size and file uploads.

  • Validate input and reject malformed requests early.

  • Use caching for expensive operations.

  • Apply async/await for efficient resource use.

  • Implement timeouts, retries, and circuit breakers.

  • Monitor and alert on unusual activity.

Conclusion

DoS/DDoS attacks are inevitable, but ASP.NET Core provides powerful features to limit, throttle, and validate requests, while infrastructure tools like WAFs and CDNs provide large-scale protection. By combining app-level safeguards with infrastructure-level defense, you can ensure that your ASP.NET Core applications remain resilient, performant, and available even under hostile traffic conditions.