GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix XSS in API Responses
in ASP.NET Core

Executive Summary

XSS in APIs occurs when user-controlled data is reflected in responses without strict Content-Type enforcement or proper encoding. While JSON is less susceptible than HTML, attackers can exploit MIME-sniffing or misconfigured endpoints to force a browser to execute malicious payloads. As a researcher, I see this most often in endpoints that manually construct responses or fail to set the 'nosniff' header.

The Vulnerable Pattern

VULNERABLE CODE
[HttpGet("profile/raw")]
public IActionResult GetRawProfile(string username)
{
    // VULNERABLE: Manually building a string response and potentially allowing type sniffing.
    // An attacker could pass  as the username.
    var htmlResponse = $"
User: {username}
"; return Content(htmlResponse, "text/html"); }

The Secure Implementation

To kill API-based XSS, follow three rules: 1. Never manually construct HTML or JS responses in your controllers. 2. Always return data as JSON via `Ok()` or `Json()` results; ASP.NET Core's default serializer (System.Text.Json) encodes characters like '<' and '>' by default. 3. Enforce the 'X-Content-Type-Options: nosniff' header globally. This prevents legacy browsers from ignoring the 'application/json' MIME type and attempting to render the response as HTML, which is the primary vector for reflected XSS in APIs.

SECURE CODE
[HttpGet("profile/secure")]
public IActionResult GetSecureProfile(string username)
{
    // SECURE: Use ObjectResult (Ok) to ensure application/json and automatic serialization.
    // System.Text.Json automatically escapes HTML-sensitive characters.
    return Ok(new { User = username });
}

// Global Middleware Configuration (Program.cs): app.Use(async (context, next) => { // SECURE: Prevent MIME-sniffing to ensure browsers don’t treat JSON as HTML. context.Response.Headers.Add(“X-Content-Type-Options”, “nosniff”); context.Response.Headers.Add(“Content-Security-Policy”, “default-src ‘none’; frame-ancestors ‘none’;”); await next(); });

System Alert • ID: 3605
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.