How to fix XSS in API Responses
in ServiceStack
Executive Summary
ServiceStack's flexibility in content negotiation is a primary attack surface. While its default JSON/CSV serializers are generally safe, manual HTML response generation via 'HtmlResult' or unencoded Razor views creates immediate Reflected XSS vulnerabilities. If user-controlled input hits the DOM without context-aware encoding, the application is compromised.
The Vulnerable Pattern
public class ProfileService : Service
{
public object Any(GetProfile request)
{
// VULNERABLE: Direct string interpolation into HtmlResult bypasses auto-serialization encoding.
// An attacker can pass ?Name=
return new HtmlResult($"User: {request.Name}
");
}
}
The Secure Implementation
The vulnerability exists because 'HtmlResult' treats the input string as a raw response body, skipping the safety checks present in structured formats like JSON. To mitigate this, developers must use the '.HtmlEncode()' extension method on all reflected DTO properties. Furthermore, implementing 'GlobalResponseFilters' to inject 'X-Content-Type-Options: nosniff' prevents browsers from MIME-sniffing non-HTML content into executable scripts, while a 'Content-Security-Policy' (CSP) provides a critical secondary defense layer to block unauthorized inline scripts.
public class ProfileService : Service { public object Any(GetProfile request) { // SECURE: Explicitly encode the user input using ServiceStack's .HtmlEncode() extension. string safeName = request.Name.HtmlEncode(); return new HtmlResult($"User: {safeName}
"); } }
// Global hardening in AppHost.Configure: this.GlobalResponseFilters.Add((req, res, dto) => { res.AddHeader(“X-Content-Type-Options”, “nosniff”); res.AddHeader(“Content-Security-Policy”, “default-src ‘self’; script-src ‘self’”); });
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.
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.