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
 HttpPostedFile file = context.Request.Files[0];
 file.SaveAs(Path.Combine(uploadDir, file.FileName));

 context.Session[key] = count + 1;
 context.Response.Write(
 "{\"fileName\":\"" + file.FileName + "\"}");
 }
}

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

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