Production engineering
Reveal answer and reasoning
Output encoding is chosen at the point where data enters a representation context. HTML element text, a URL and a JavaScript expression have different parsing rules, so a value should not receive a universal safe-string label. The external /encoded endpoint places an encoded name inside one HTML paragraph and declares an HTML content type. That is a narrow, inspectable contract.
The surrounding document intentionally contains trusted markup, while only the untrusted text fragment must have its markup delimiters represented as data. A successful check of that fragment does not certify every context or browser path in an application.
SecurityLabs.cs reads the optional name query parameter, applies HtmlEncoder.Default.Encode to that string and concatenates the result between trusted paragraph boundaries. Results.Content supplies text/html with UTF-8. The external check requests markup-like input with proper URL encoding, then inspects the returned bytes and content type. The encoded fragment should display as literal text if rendered in that stated context. The full response naturally still contains its own document and paragraph delimiters.
Looking for every angle bracket to be absent from the entire response would therefore test the wrong contract and reject the intentionally valid surrounding HTML.
What a strong answer covers
- Output encoding is chosen at the point where data enters a representation context.
- SecurityLabs.cs reads the optional name query parameter, applies HtmlEncoder.Default.Encode to that string and concatenates the result between trusted paragraph boundaries.
- Encoding is not a replacement for validating a URL's allowed scheme, authenticating a caller or authorizing access to data.
Common pitfall
Encoding is not a replacement for validating a URL's allowed scheme, authenticating a caller or authorizing access to data. It also does not add a Content Security Policy or prove that downstream code never decodes and reinserts text into a dangerous context. A future change from paragraph text to script content needs an independent design rather than reusing a previously encoded value. Storing encoded text as a universal representation can additionally produce double encoding or make later contexts harder to reason about. Preserve original data where appropriate and encode at the actual output boundary with the intended context visible.
Follow-up questions
- Why would checking that the entire HTML document contains no angle brackets be an incorrect test of this endpoint?
- How can pre-encoding stored text lead to double encoding when a later view encodes it again?
Self-review
Choose what to revisit. These marks are your own assessment and are separate from lesson completion.