MMayel Engineering
All posts

A spam-free contact form with a small .NET Minimal API

How I protected the contact form on this website with a honeypot, rate limiting and proper validation, without a captcha and without a third-party service.

  • .NET
  • ASP.NET Core
  • Security

The problem

A contact form on a public website becomes a target for bots within days. The usual fixes have drawbacks: a captcha annoys real visitors, and an external form service sends your prospects’ data through someone else’s servers.

I wanted something small that I understand and run myself.

The solution

A Minimal API with exactly one endpoint. Four things make the difference.

1. A honeypot instead of a captcha. The form contains a field called website that humans never see. Bots fill it in anyway. The API then answers 202 Accepted but sends nothing. The bot never notices it was caught.

public bool IsSpam => !string.IsNullOrWhiteSpace(Website);

2. Rate limiting per IP. ASP.NET Core has shipped this since .NET 7. Five requests in ten minutes is plenty for any human.

options.AddPolicy("contact", context => RateLimitPartition.GetFixedWindowLimiter(
    context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
    _ => new FixedWindowRateLimiterOptions
    {
        PermitLimit = 5,
        Window = TimeSpan.FromMinutes(10),
        QueueLimit = 0,
    }));

3. Validation on the server, not just in the browser. Checks in the browser are a convenience. Security only happens on the server: required fields, maximum lengths and a real check of the email address. Errors go back as a ValidationProblem, so the form can highlight the affected fields.

4. Never put user input into mail headers. The sender of the email is always my own address. The visitor’s address only goes into Reply-To, and line breaks are stripped from the name before it ends up in the subject.

private static string ToSingleLine(string value) =>
    value.ReplaceLineEndings(" ").Trim();

What I take away

A contact form needs neither a captcha nor a third-party provider. An invisible field, a rate limit and honest server-side validation keep most of the spam out. And prospects’ data stays on my own system.