Input validation and output encoding
Input validation and output encoding
Validation decides whether input belongs in your application; output encoding represents data safely in a particular output context. They solve different problems. A valid product title can contain an ampersand, which must be encoded when rendered as HTML text. A rejected quantity must never reach the inventory update.
Validate at the server boundary: enforce required fields, length, numeric range, allowed values and cross-field business rules. Reject rather than silently reinterpret invalid input. Client validation helps usability but is not a trusted security boundary. Encode HTML text with the appropriate encoder or Razor's normal encoding; HTML, JavaScript, URL and SQL contexts are different. Do not treat HTML encoding as SQL protection: bind values with database parameters as taught in chapter 29. XSS defenses include safe rendering and avoiding raw HTML from untrusted input. CSRF protection applies when browser credentials are automatically attached; CORS governs browser cross-origin access, not caller authorization. SSRF prevention requires controlled destinations, DNS and address checks where appropriate, redirect controls and network egress restrictions; a string prefix alone is not sufficient. For uploads, enforce body size, actual type and storage policy, assign server-generated names and keep uploads outside executable/public paths by default. Bound deserialization and parsing, use explicit DTOs and reject invalid business state. Rate limiting bounds accepted work but is not a substitute for authorization; per-process counters are not a distributed quota. Threat model the asset, trust boundary, failure mode and control, then test both rejection and permitted behavior. These offline examples test only local defensive functions, not browser, database or network behavior.
Baseline: .NET 10 / C# 14 with Microsoft.AspNetCore.App shared framework. All snippets are independent console fixtures, not ByteMind runner code. In an approved isolated environment with a reviewed installed SDK and targeting packs, use dotnet build and dotnet run --no-build in the fixture directory; restore only from approved sources if required. No external service, real user data, account or credential is needed. Expected results are reasoned, not executed; cryptographic random data is not printed.
Validate a bounded inventory quantity
Require a plain unsigned decimal integer from 1 to 25; the invariant culture and NumberStyles.None make accepted syntax explicit.
using System.Globalization;foreach (var input in new[] { "12", "0", "26", "1.5", " 4" }) { var valid = int.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out int quantity) && quantity is >= 1 and <= 25; Console.WriteLine(valid ? $"accepted:{quantity}" : "rejected");}Expected output (not executed):
accepted:12rejectedrejectedrejectedrejectedParsing alone is insufficient: zero and 26 parse successfully but violate the business contract. No database update occurs here.
Encode ordinary text for HTML
A fictional title contains an ampersand. Encode it at the HTML text boundary, not when storing its canonical value.
using System.Text.Encodings.Web;var title = "Tea & Books";var encoded = HtmlEncoder.Default.Encode(title);Console.WriteLine(encoded);Console.WriteLine(title == "Tea & Books");Expected output (not executed):
Tea & BooksTrueThe HTML representation contains an entity while the stored string is unchanged. For URLs or JavaScript use context-appropriate APIs; do not concatenate untrusted input into script or raw HTML.
Bound concurrent work without a waiting queue
A concurrency limiter grants one lease at a time. This is a local component test using no HTTP traffic.
using System.Threading.RateLimiting;using var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions { PermitLimit = 1, QueueLimit = 0, QueueProcessingOrder = QueueProcessingOrder.OldestFirst});using (var first = limiter.AttemptAcquire(1)) { using var second = limiter.AttemptAcquire(1); Console.WriteLine(first.IsAcquired); Console.WriteLine(second.IsAcquired);}using var third = limiter.AttemptAcquire(1);Console.WriteLine(third.IsAcquired);Expected output (not executed):
TrueFalseTrueReleasing the first lease makes capacity available. This controls simultaneous work, not requests per minute, and is local to this limiter instance.
Apply the concept
A book-cover upload accepts JPEG or PNG and a caption. Design an input contract and output rendering policy. Include file size, content checks, filename generation, storage location, authorization and caption rendering.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these fixtures as production security controls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Input validation and output encoding — knowledge check
Apply the lesson concepts to the following scenarios.
A title contains an ampersand. Which is appropriate for HTML text?
A quantity of 26 parses successfully but maximum is 25. What next?
Does a restrictive CORS policy replace API authorization?
What does a concurrency limiter bound?
Which upload name should determine the server path?