Skip to main content

Lesson 5 of 8

Input Sanitization & XSS Prevention

XSS (Cross-Site Scripting) attacks inject malicious JavaScript into data returned by your API and rendered by clients. ASP.NET Core automatically HTML-encodes Razor output, but APIs returning raw HTML or rich text stored in DB need explicit sanitization.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Sanitizing HTML & Preventing XSS

Sanitizing HTML & Preventing XSS
// ━━ HTML sanitization for user-submitted rich text (blog posts, comments) ━━
// dotnet add package Ganss.Xss

using Ganss.Xss;

public class HtmlSanitizerService
{
    private readonly HtmlSanitizer _sanitizer;

    public HtmlSanitizerService()
    {
        _sanitizer = new HtmlSanitizer();

        // Allow only safe HTML elements
        _sanitizer.AllowedTags.Clear();
        _sanitizer.AllowedTags.UnionWith(new[] { "p", "br", "strong", "em", "ul", "ol", "li", "a", "blockquote", "code", "pre", "h2", "h3", "h4" });

        // Allow only safe attributes
        _sanitizer.AllowedAttributes.Clear();
        _sanitizer.AllowedAttributes.UnionWith(new[] { "href", "title" });

        // Allow only safe URL schemes for href
        _sanitizer.AllowedSchemes.Clear();
        _sanitizer.AllowedSchemes.UnionWith(new[] { "https", "mailto" });
    }

    public string Sanitize(string html) => _sanitizer.Sanitize(html);
}

// ━━ Usage in service ━━
public class BlogPostService(HtmlSanitizerService sanitizer)
{
    public async Task<Post> CreateAsync(CreatePostRequest request, CancellationToken ct)
    {
        var post = new Post
        {
            Title = HtmlEncoder.Default.Encode(request.Title), // encode title (plain text context)
            Content = sanitizer.Sanitize(request.Content),      // sanitize HTML content
        };
        // save...
        return post;
    }
}

// ━━ JSON injection prevention ━━
// Never serialize user-controlled strings into JSON without escaping
// System.Text.Json does this correctly by default - do NOT use string concatenation for JSON

// BAD:
// var json = $'{{ "name": "{userInput}" }}'; // injection: userInput = '", "admin": true'

// GOOD: use System.Text.Json serialization
var json = System.Text.Json.JsonSerializer.Serialize(new { name = userInput }); // properly escaped

// ━━ HtmlEncoder for plain text in HTML context ━━
// In API responses, use System.Text.Encodings.Web.HtmlEncoder if building any HTML strings

class Post { public Guid Id { get; set; } public string Title { get; set; } = ""; public string Content { get; set; } = ""; }
record CreatePostRequest(string Title, string Content);
string userInput = "";

Tip

Tip

Practice Input Sanitization XSS Prevention in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Input Sanitization XSS Prevention from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Input Sanitization XSS Prevention is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done