Rate Limiting

Rate Limiting

Apply rate limiting to upload endpoints to prevent abuse. Limit the number of uploads per user per time window using session-based tracking in the upload handler.

Drag & drop files here, or paste from clipboard
<%-- Upload handler with session-based rate limiting --%>
public class UploadHandler : IHttpHandler, IRequiresSessionState
{
 private const int MaxUploadsPerMinute = 10;

 public void ProcessRequest(HttpContext context)
 {
 // Track uploads per session
 var key = "UploadCount";
 var timestampKey = "UploadWindowStart";

 DateTime windowStart = context.Session[timestampKey]
 as DateTime? ?? DateTime.MinValue;
 int count = context.Session[key] as int? ?? 0;

 // Reset window if expired
 if ((DateTime.UtcNow - windowStart).TotalMinutes >= 1)
 {
 count = 0;
 windowStart = DateTime.UtcNow;
 context.Session[timestampKey] = windowStart;
 }

 if (count >= MaxUploadsPerMinute)
 {
 context.Response.StatusCode = 429;
 context.Response.Write(
 "Too many uploads. Please try again later.");
 return;
 }

 // Process upload
 if (context.Request.Files.Count == 0)
 {
 context.Response.StatusCode = 400;
 context.Response.Write("No file was posted.");
 return;
 }

 HttpPostedFile file = context.Request.Files[0];
 string safeName = Path.GetFileName(file.FileName ?? string.Empty);
 if (safeName.Length == 0)
 {
 context.Response.StatusCode = 400;
 context.Response.Write("Invalid file name.");
 return;
 }
 file.SaveAs(Path.Combine(uploadDir, safeName));

 context.Session[key] = count + 1;
 context.Response.ContentType = "application/json";
 context.Response.Write(
 "{\"fileName\":\"" +
 HttpUtility.JavaScriptStringEncode(safeName) + "\"}");
 }
}

<%-- web.config: configure rate limit settings --%>
<appSettings>
 <add key="UploadRateLimit" value="10" />
 <add key="UploadRateWindowSeconds" value="60" />
</appSettings>

<%-- Client-side: handle 429 status --%>
<script>
var statusEl = document.getElementById('uploadStatus');
AjaxUploader.create(el, {
 uploadUrl: '/ajaxupload.axd/upload',
 onError: function (file, error) {
 if (error.status === 429) {
 statusEl.textContent = 'Upload limit reached. Please wait.';
 }
 }
});
</script>