GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix XSS in API Responses
in .NET 8 Web API

Executive Summary

XSS in APIs occurs when untrusted input is reflected in the response without proper validation or encoding, allowing attackers to execute scripts in the context of the victim's browser. Even if you're returning JSON, misconfigured headers or manual string concatenation can lead to disaster. In .NET 8, the goal is to enforce strict Content-Types and use built-in encoders to neutralize the threat.

The Vulnerable Pattern

VULNERABLE CODE
[HttpGet("echo")]
public IActionResult Get(string input)
{
    // VULNERABILITY: Manually constructing a response with user input
    // and setting an insecure Content-Type or allowing the browser to sniff it.
    var html = $"

User Input: {input}

"; return Content(html, "text/html"); }

The Secure Implementation

To kill XSS in .NET 8: 1. Always prefer application/json; System.Text.Json automatically escapes HTML-sensitive characters like <, >, and &. 2. If you must return HTML, use the 'HtmlEncoder' from 'System.Text.Encodings.Web' to sanitize data before it hits the sink. 3. Set the 'X-Content-Type-Options: nosniff' header globally to prevent browsers from interpreting non-HTML content as script. 4. Use Content Security Policy (CSP) headers to restrict where scripts can execute from, providing a final layer of defense.

SECURE CODE
[HttpGet("echo")]
public IActionResult Get(string input, [FromServices] HtmlEncoder encoder)
{
    // OPTION 1: Return JSON (Preferred). System.Text.Json escapes tags by default.
    // return Ok(new { Data = input });
// OPTION 2: If HTML is required, use context-aware encoding.
string safeInput = encoder.Encode(input);
return Content($"<html><body><h1>User Input: {safeInput}</h1></body></html>", "text/html");

}

System Alert • ID: 8664
Target: API Responses API
Potential Vulnerability

Your API Responses API might be exposed to XSS

74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.