Skip to main content

🛡️ Defending Your .NET API Against DDoS Attacks: A Practical Guide

Published 4 min readMarkdown

A DDoS attack (Distributed Denial of Service) is a malicious attempt to disrupt the normal traffic of a targeted server, service, or network by overwhelming it with a flood of internet traffic.


🔍 How It Works:

  • Distributed: The attack comes from many different sources, often from a network of infected computers (called a botnet).

  • Denial of Service: The target becomes unavailable to legitimate users because it's overloaded with fake traffic.


💥 Common Types of DDoS Attacks:

  1. Volume-Based Attacks

    • Goal: Consume all available bandwidth.

    • Example: UDP floods, ICMP floods.

    • Measured in: Gbps (Gigabits per second)

  2. Protocol Attacks

    • Goal: Exploit weaknesses in Layer 3 and 4 protocols (e.g., TCP/IP).

    • Example: SYN flood, Ping of Death.

    • Measured in: Packets per second (PPS)

  3. Application Layer Attacks

    • Goal: Target Layer 7 (HTTP/HTTPS) where web pages are generated.

    • Example: HTTP flood, Slowloris.

    • Measured in: Requests per second (RPS)


⚠️ Real-World Consequences:

  • Downtime for websites or apps.

  • Loss of revenue and reputation.

  • Security teams may miss other intrusions while dealing with the flood.


🛡️ Prevention & Mitigation:

  • Use Web Application Firewalls (WAF).

  • Employ rate limiting and traffic filtering.

  • Partner with CDNs or DDoS protection services like Cloudflare or AWS Shield.

  • Monitor traffic for abnormal patterns.


Let me know if you want a diagram or code-level example related to .NET or networking security practices for handling DDoS threats.

✅ Diagram: What a DDoS Attack Looks Like

Here's a basic representation:

  [Bot 1]         [Bot 2]         [Bot 3]         [Bot N]
     |               |               |               |
     +---------------+---------------+---------------+
                                 ↓
                    [Your .NET API Server (Target)]
                          ↑         ↑
                    Legitimate users get denied

🧰 Step-by-Step Mitigation in .NET Web API

While you can’t stop a full-scale DDoS (especially at the infrastructure level) from code alone, you can reduce the impact with smart coding and proper configurations.


🔐 1. Rate Limiting

Use a middleware like AspNetCoreRateLimit.

🛠️ Setup:

Install via NuGet:

dotnet add package AspNetCoreRateLimit

Configure in Program.cs:

builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

app.UseIpRateLimiting();

Add to appsettings.json:

"IpRateLimiting": {
  "EnableEndpointRateLimiting": true,
  "StackBlockedRequests": false,
  "RealIpHeader": "X-Real-IP",
  "ClientIdHeader": "X-ClientId",
  "HttpStatusCode": 429,
  "GeneralRules": [
    {
      "Endpoint": "*",
      "Period": "1s",
      "Limit": 5
    },
    {
      "Endpoint": "*",
      "Period": "1m",
      "Limit": 100
    }
  ]
}

🛡️ 2. Throttle Resource-Intensive Endpoints

Limit or defer heavy operations like report generation, file uploads, or PDF creation:

[HttpPost]
[Route("generate-heavy-report")]
public async Task<IActionResult> GenerateReport(CancellationToken token)
{
    if (!IsRequestAllowed(Request))
        return StatusCode(429, "Too Many Requests");

    var report = await _reportService.GenerateAsync(token);
    return File(report, "application/pdf");
}

🔍 3. Use Application Firewall / CDN

Offload protection to services before requests reach your .NET server:

  • 🛡️ Cloudflare, AWS Shield, or Azure Front Door

  • 🌐 Reverse proxy (e.g., NGINX or Azure Application Gateway)


🧪 4. Detect Patterns via Logs

Use structured logging (e.g., Serilog + Seq) to identify high-frequency IPs.

Log.Information("Request from IP: {IP}", HttpContext.Connection.RemoteIpAddress);

Later, you can aggregate and analyze in a dashboard like Kibana, Grafana, or Seq.


🧰 5. Caching to Reduce Repeated Computation

Use MemoryCache or ResponseCache for GET endpoints:

[HttpGet]
[ResponseCache(Duration = 60)]
public IActionResult GetPublicData()
{
    var data = _service.GetCachedData();
    return Ok(data);
}

⚙️ 6. Enable Connection Limits (Infrastructure Level)

On IIS / Kestrel / nginx, configure:

  • Max connections

  • Max requests per second

  • Timeouts

For Kestrel, in appsettings.json:

"Kestrel": {
  "Limits": {
    "MaxConcurrentConnections": 100,
    "MaxRequestBodySize": 10485760
  }
}

📦 Optional: Cloudflare DDoS Protection

If you're hosting the API behind a domain, you can enable Cloudflare’s DDoS protection in their dashboard, which will:

  • Filter malicious traffic.

  • Challenge bots.

  • Log/report events.


✅ Summary Checklist

DefenseLevelTool
Rate LimitingAppAspNetCoreRateLimit
Firewall RulesInfraIIS / Azure / Cloudflare
CachingAppResponseCache, IMemoryCache
Logging & DetectionAppSerilog + Seq
CDN + Edge ProtectionEdgeCloudflare / Azure Front Door
AlertingMonitoringApplication Insights / Prometheus

No comments yet. Be the first to comment.