XSS Prevention in ASP.NET Core Using HTML Sanitization | PIT Solutions

Samadhan Banda Salagar By Samadhan Banda Salagar on March 25, 2026

Learn how PIT Solutions implements XSS prevention in ASP.NET Core using HTML sanitization with Ganss.Xss to secure web applications from malicious scripts.

Introduction

At PIT Solutions, building secure and scalable web applications is a top priority. Modern applications often accept user-generated content such as comments and rich text inputs, which can introduce serious security risks.

XSS Prevention in ASP.NET Core is essential when handling such dynamic content, as attackers can inject malicious scripts if input is not properly sanitized. One of the most widespread vulnerabilities targeting web applications today is Cross-Site Scripting (XSS), which can lead to session theft, account hijacking, data exfiltration, and malicious redirects.

For enterprise ASP.NET Core applications, preventing XSS attacks is critical especially when accepting user-generated HTML content such as blog posts, comments, or rich-text editor output. Without proper HTML sanitization in ASP.NET Core, even a single unsanitized input field can expose your entire user base to exploitation.

In this article, we explore how PIT Solutions uses HTML sanitization in ASP.NET Core with the Ganss.Xss library to implement robust ASP.NET Core XSS protection and ensure secure, reliable web applications for our clients.

What is Cross-Site Scripting (XSS)?

Cross-Site Scripting (XSS) is a security vulnerability that occurs when an application renders untrusted user input without properly sanitizing or encoding it. This allows attackers to inject executable scripts into web pages viewed by other users.

Consider a simple example where user input is displayed directly on a webpage:

If the application stores or displays this content without sanitization, the browser executes the injected script. This allows attackers to run arbitrary JavaScript within the application context, with the same permissions as the legitimate page.

The consequences can be severe: session theft, privilege escalation, credential harvesting, and full data manipulation — all triggered invisibly from the victim's browser.

 

Types of XSS Attacks

Understanding the different forms of Cross-Site Scripting helps developers design comprehensive ASP.NET Core security defenses.

1. Stored XSS

Stored XSS (also called Persistent XSS) occurs when malicious input is stored in the database and executed every time a user loads the affected page. A malicious user submits:

If stored in a comment field without sanitization, every user who views that comment will unknowingly execute the script. This is the most dangerous form of XSS because a single injection can affect all users of the platform.

If stored in a comment field without sanitization, every user who views that comment will unknowingly execute the script. This is the most dangerous form of XSS because a single injection can affect all users of the platform.

2. Reflected XSS

Reflected XSS occurs when malicious scripts are embedded in request parameters and immediately reflected in the server's response without sanitization. This often exploits search fields, error messages, or URL parameters:

If the search query is rendered directly into the HTML response without encoding or sanitization, the browser executes the injected script. Attackers deliver these via phishing links.

3. DOM-Based XSS

DOM-Based XSS occurs when client-side JavaScript reads from untrusted data sources (such as the URL fragment) and writes it into the DOM without sanitization:

Since DOM-based XSS is processed entirely in the browser, server-side encoding alone is insufficient. Proper sanitize HTML in .NET techniques must be complemented by client-side validation as well.

What is HTML Sanitization?

HTML sanitization in ASP.NET Core is the process of cleaning user-provided HTML input by removing unsafe elements and attributes while preserving legitimate, safe formatting tags. Unlike output encoding (which escapes all HTML), sanitization intelligently allows a defined allowlist of safe elements to pass through.

A properly configured HTML sanitizer removes:

  • <script> tags and inline JavaScript
  • Event handler attributes (onclick, onerror, onload, etc.)
  • Malicious URLs using javascript: protocol schemes
  • Unsafe iframe, object, and embed elements
  • Any other attributes or tags not on the explicit allowlist

While preserving safe formatting elements like <p>, <b>, <i>, <ul>, <a href> (with validated URLs), and similar benign tags.

Example — Input (potentially malicious):

The malicious <script> and event handlers are completely removed while legitimate formatting remains intact — this is precisely what ASP.NET Core XSS protection through sanitization achieves.

Why Use Ganss.Xss in ASP.NET Core?

The Ganss.Xss library is the leading .NET library purpose-built for HTML sanitization in ASP.NET Core. It is the recommended choice for teams looking to prevent XSS attacks in .NET without implementing complex parsing logic from scratch.

Key advantages include:

  • Lightweight and performant: minimal overhead, suitable for high-throughput APIs
  • Highly configurable: define precise allowlists of tags and attributes
  • Supports attribute filtering: granular control over which attributes are permitted per tag
  • URL scheme validation: blocks javascript: and data: URI schemes automatically
  • Easy DI integration: designed for ASP.NET Core's dependency injection system
  • Actively maintained: regular updates address emerging XSS vectors

Compared to building custom regex-based filters (which are notoriously brittle and incomplete), Ganss.Xss provides a battle-tested HTML parser that handles edge cases, nested tags, and encoding tricks that manual approaches routinely miss.

Step-by-Step Implementation

Here is how to implement XSS prevention in ASP.NET Core using the Ganss.Xss library in a production-grade, enterprise application.

Step 1: Installing the Library

Install Ganss.Xss via the .NET CLI or NuGet Package Manager:

Once installed, it can be integrated into the application as a reusable service.

Step 2: Designing a Sanitization Service

In enterprise applications, HTML sanitization in ASP.NET Core should be centralized in a dedicated service class rather than scattered across individual controllers. This ensures consistent sanitization behavior throughout the application:

This service defines an explicit allowlist of permitted HTML tags and automatically strips all others — a core Cross-Site Scripting prevention pattern.

Step 3: Registering the Service

Register the sanitizer service as a singleton in Program.cs for optimal performance. Since the sanitizer configuration is stateless and does not change per request, reusing the instance avoids unnecessary instantiation overhead:

Step 4: Using the Sanitizer in a Controller

Inject the sanitizer service into your API controllers via constructor injection. Before saving any user-provided HTML content, always run it through the sanitizer:

This ensures that even if a client bypasses frontend validation, the server-side sanitize HTML in .NET layer will neutralize any malicious payloads before they reach the database or response stream.

Testing XSS Protection

Always test your ASP.NET Core XSS protection implementation against known malicious payloads before deploying to production. Use a variety of inputs representing different XSS vectors:

Input (Malicious)/Output:

Additionally, test edge cases such as nested tags (<scr<script>ipt>), encoded payloads (%3Cscript%3E), and CSS expression attacks. The Ganss.Xss parser handles these correctly because it uses a proper HTML parser rather than regex.

Best Practices for XSS Prevention in ASP.NET Core

Implementing Ganss.Xss is just one component of a comprehensive Cross-Site Scripting prevention strategy. Follow these best practices as part of a defense-in-depth approach:

  • Always sanitize before saving to the database — never trust client-side validation alone
  • Allow only the minimum required HTML tags — start with the most restrictive allowlist and expand only when needed
  • Never permit event attributes — block onclick, onerror, onload, onmouseover, and all other event handlers
  • Restrict URL schemes to http and https only — prevents javascript: and data: URI exploits
  • Implement Content Security Policy (CSP) headers — adds a browser-level defense layer against script injection
  • Enable ASP.NET Core's built-in output encoding — use Razor's automatic HTML encoding as a secondary defense
  • Validate on both client and server — never rely solely on one layer
  • Keep Ganss.Xss updated — new XSS vectors emerge regularly; stay current with library updates

How PIT Solutions Ensures Secure ASP.NET Applications

At PIT Solutions, security is not an afterthought — it is woven into every stage of our ASP.NET Core development services, from architecture design through post-deployment monitoring. Our development approach to ASP.NET Core security includes:

  • Centralized HTML sanitization using Ganss.Xss — integrated as a singleton service for consistent XSS prevention in ASP.NET Core across all endpoints
  • Secure coding practices — rigorous input validation, output encoding, and parameterized queries to prevent injection attacks
  • Defense-in-depth architecture — combining CSP headers, server-side validation, HTTPS enforcement, and anti-CSRF tokens
  • Regular security testing — automated DAST scanning, manual penetration testing, and code reviews focused on OWASP Top 10 vulnerabilities
  • OWASP-aligned development — our teams follow OWASP guidelines and stay current with emerging Cross-Site Scripting prevention techniques

Whether you need a secure web application development partner or want to audit and harden an existing ASP.NET Core application, PIT Solutions brings the expertise and processes to deliver secure, scalable software your users can trust.

Conclusion

XSS Prevention in ASP.NET Core is a non-negotiable requirement for any modern web application that handles user-generated content. The combination of the Ganss.Xss library for HTML sanitization in ASP.NET Core, server-side output encoding, and a strong Content Security Policy provides a robust, layered defense against Cross-Site Scripting attacks.

By centralizing sanitization logic, registering it as a singleton, and applying it consistently before every database write or response, developers can substantially reduce their application's attack surface with minimal performance overhead.

At PIT Solutions, we integrate these ASP.NET Core security practices into every project we deliver. Our security-first development culture, combined with proven tools like Ganss.Xss, ensures that the web applications we build are resilient against XSS and the full spectrum of web application vulnerabilities. Building secure software is not just a technical discipline — it is a commitment we make to every client.

Ready to prevent XSS attacks in .NET and secure your web applications?
Partner with PIT Solutions — your trusted ASP.NET Core development partner for enterprise-grade security.

Contact us today and let our experts help you build secure, scalable, and future-ready applications.

Related Blogs

How .NET 8 Minimal APIs Helped PIT Solutions Replace Bloated Controllers

Dapper vs EF Core: How PIT Solutions Boosted API Performance with a Hybrid Approach