This is sort of the source for preventing XSS in ASP.NET (at least from Microsoft):

How To: Prevent Cross-Site Scripting in ASP.NET

Some important things to glean from the article specific to your question:

  • Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases.

  • use HttpUtility.UrlEncode to encode output URLs if they are constructed from input.

Regarding HTMLAttributeEncode:

  • The HtmlAttributeEncode method converts only quotation marks ("), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.

  • The string result from the HtmlAttributeEncode method should be used only for double-quoted attributes. Security issues might arise when using the HtmlAttributeEncode method with single-quoted attributes.

And finally, with UriEscapeString, use that if what you are escaping is a URI. This SO question discusses the difference between UriEscapeString and UriEscapeDataString.

Answer from Gray on Stack Exchange
🌐
Evuln
evuln.com › tools › xss-encoder
XSS String Encoder
Generate XSS code using XSS String Encoder. Check your input validation filters against XSS.
🌐
OWASP
owasp.org › www-project-java-encoder
OWASP Java Encoder | OWASP Foundation
This project will help Java web developers defend against Cross Site Scripting! Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts (primarily JavaScript) are injected into otherwise trusted web sites.
🌐
PortSwigger
portswigger.net › web-security › cross-site-scripting › contexts
Cross-site scripting contexts | Web Security Academy
When the browser has parsed out the HTML tags and attributes within a response, it will perform HTML-decoding of tag attribute values before they are processed any further. If the server-side application blocks or sanitizes certain characters that are needed for a successful XSS exploit, you can often bypass the input validation by HTML-encoding those characters.
🌐
Medium
larbi-ouiyzme.medium.com › understanding-payload-obfuscation-and-encoding-in-xss-attacks-and-waf-bypass-techniques-3c9b5397d000
Understanding payload obfuscation and encoding in XSS attacks and WAF bypass techniques | by Larbi OUIYZME | Medium
May 9, 2025 - Attackers use various encoding and obfuscation techniques to bypass security controls implemented in web applications. These methods aim to hide malicious payloads to avoid detection by filtering systems such as WAFs, vulnerability scanners, or input parsers. This article explores the most common techniques, particularly in the context of Cross-Site Scripting (XSS) attacks, and illustrates how they are used to make attacks more stealthy.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › Security › Attacks › XSS
Cross-site scripting (XSS) - Security | MDN
You searched for <img src=x onerror=alert('XSS!')>. Similarly, if you're doing client-side rendering with React, values embedded in JSX are automatically encoded.
Find elsewhere
🌐
GitHub
github.com › cyberwitchery › contextual-encoder
GitHub - cyberwitchery/contextual-encoder: contextual output encoding for XSS defense, co-evolved with LLMs · GitHub
5 days ago - contextual output encoding for XSS defense and safe literal embedding, inspired by the OWASP Java Encoder.
Author   cyberwitchery
🌐
OWASP Cheat Sheet Series
cheatsheetseries.owasp.org › cheatsheets › Cross_Site_Scripting_Prevention_Cheat_Sheet.html
Cross Site Scripting Prevention - OWASP Cheat Sheet Series
Please look at the OWASP Java Encoder JavaScript encoding examples for examples of proper JavaScript use that requires minimal encoding. For JSON, verify that the Content-Type header is application/json and not text/html to prevent XSS.
🌐
PortSwigger
portswigger.net › web-security › cross-site-scripting
What is cross-site scripting (XSS) and how to prevent it? | Web Security Academy
How do I prevent XSS in Java? Filter your inputs with a whitelist of allowed characters and use a library such as Google Guava to HTML-encode your output for HTML contexts, or use JavaScript Unicode escapes for JavaScript contexts.
🌐
OpenMRS
talk.openmrs.org › development
Use OWASP Encoder for XSS attacks - Development - OpenMRS Talk
December 18, 2015 - The org.apache.commons.lang.StringEscapeUtils is also a solution for this. But there are some issues which are introduce in [1] when used this. OWASP Java Encoder [2] is recently used widely to prevent XSS attacks.
Top answer
1 of 9
96

No.

Putting aside the subject of allowing some tags (not really the point of the question), HtmlEncode simply does NOT cover all XSS attacks.

For instance, consider server-generated client-side javascript - the server dynamically outputs htmlencoded values directly into the client-side javascript, htmlencode will not stop injected script from executing.

Next, consider the following pseudocode:

<input value=<%= HtmlEncode(somevar) %> id=textbox>

Now, in case its not immediately obvious, if somevar (sent by the user, of course) is set for example to

a onclick=alert(document.cookie)

the resulting output is

<input value=a onclick=alert(document.cookie) id=textbox>

which would clearly work. Obviously, this can be (almost) any other script... and HtmlEncode would not help much.

There are a few additional vectors to be considered... including the third flavor of XSS, called DOM-based XSS (wherein the malicious script is generated dynamically on the client, e.g. based on # values).

Also don't forget about UTF-7 type attacks - where the attack looks like

+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4-

Nothing much to encode there...

The solution, of course (in addition to proper and restrictive white-list input validation), is to perform context-sensitive encoding: HtmlEncoding is great IF you're output context IS HTML, or maybe you need JavaScriptEncoding, or VBScriptEncoding, or AttributeValueEncoding, or... etc.

If you're using MS ASP.NET, you can use their Anti-XSS Library, which provides all of the necessary context-encoding methods.

Note that all encoding should not be restricted to user input, but also stored values from the database, text files, etc.

Oh, and don't forget to explicitly set the charset, both in the HTTP header AND the META tag, otherwise you'll still have UTF-7 vulnerabilities...

Some more information, and a pretty definitive list (constantly updated), check out RSnake's Cheat Sheet: http://ha.ckers.org/xss.html

2 of 9
8

If you systematically encode all user input before displaying then yes, you are safe you are still not 100 % safe.
(See @Avid's post for more details)

In addition problems arise when you need to let some tags go unencoded so that you allow users to post images or bold text or any feature that requires user's input be processed as (or converted to) un-encoded markup.

You will have to set up a decision making system to decide which tags are allowed and which are not, and it is always possible that someone will figure out a way to let a non allowed tag to pass through.

It helps if you follow Joel's advice of Making Wrong Code Look Wrong or if your language helps you by warning/not compiling when you are outputting unprocessed user data (static-typing).

🌐
R3zk0n
x64.sh › posts › XSS-Gen
XSS Encoding Generator | R3zk0n
January 19, 2021 - Typically during penetration testing, I tend to want to generate a number of payloads using various encoding methods to test for cross-scripting bypasses, some WAF’s might block ( however using &lpar; can aid in bypassing it, and browsing to various other websites to generate a number of payloads can be a bit tedious, So I quickly wrote this tool one night to generate a various number of encoded payloads to aid in penetration testing.
🌐
Medium
medium.com › @DhruxMan › hex-encoding-in-xss-a-sneaky-bypass-story-5c413aec49b5
Hex Encoding in XSS: A Sneaky Bypass Story | by DHRUxMAN | Medium
March 5, 2025 - Upon testing, I noticed that the application filtered common XSS payloads like <script>alert(1)</script> by escaping < and > characters. However, the application failed to sanitize hex-encoded characters, which presented an interesting opportunity.
🌐
Sonar
sonarsource.com › blog › encoding-differentials-why-charset-matters
Encoding Differentials: Why Charset Matters | Sonar
July 15, 2024 - Encoding differentials occur when different layers of a web application interpret the same byte sequence under different character sets, creating security gaps that bypass input validation. Charset mismatches between the browser, server, and database can allow attackers to smuggle malicious payloads—such as XSS or SQL injection—past filters that rely on consistent encoding.
🌐
Medium
infosecwriteups.com › got-another-xss-using-double-encoding-e6493a9f7368
Reflected XSS using Double Encoding | by ag3n7 | InfoSec Write-ups
December 6, 2022 - This attack technique consists of encoding user request parameters twice in hexadecimal format to bypass security controls or cause unexpected behavior from the application.
🌐
Invicti
invicti.com › learn › cross-site-scripting-xss
Cross-Site Scripting (XSS) Vulnerability Guide
Scripts are everywhere in modern applications, so there is no single fix that eliminates all cross-site scripting. Effective XSS prevention requires layered security measures. Most modern application frameworks automatically perform output encoding by default.
Top answer
1 of 1
1

You encode data (strictly speaking, only data that might include user input, but many times it's just easier to apply to all data) right before it gets inserted into the page DOM. In different scenarios this means different things, and that results in a lot of confusion.

To answer one of your questions directly, you do not encode data before sending it to the server, or before inserting it into a database or something. You don't encode data on the request side in general. The reason is that in a complex application, you don't know where and in what context your data will be rendered, and for different contexts you will potentially need different encodings. Your input layer has nothing to do with that, but this is not just an architectural question, you have no way to select an encoding until you know how you want to render that data.

Of course this does not mean you don't encode it to whatever "output" it gets right into, during the request. For example you apply encoding to prevent SQL injection if you have an SQL database, but that is done automatically by using proper data access layers, parameterized queries and so on. You also apply an appropriate xml encoding if it gets into an XML during the request and so on. But that is not about XSS, it's about preventing other injection vulnerabilities, and these things are likely done by your language or framework mostly automatically, unless you are doing something unusual or less frequent.

You also apply input validation to any input, you can validate for format (in case of say an email address or a date), or you can validate for desired character set and so on.

But in general, there is nothing wrong with storing data as you received it from the client, without any actual encoding. In fact, this is the right thing to do in most cases (see below for the exception).

Then whenever that data gets output in any way, rendered in HTML, used in a backend query (which can be LDAP or SMTP or SQL or whatever else), you apply the appropriate encoding, according to this context you are using your data in. For html you apply html encoding, but for example for javascript (html can contain javascript blocks, where this also applies!) you apply javascript encoding. This is an output thing in general.

Having said that, there are a few... well, let's call them special cases.

Modern javascript applications (like single page frontends) might manage a lot of data without talking to a server. User input sometimes gets written all over the place and so on. In that case it's the job of the SPA to apply appropriate encoding whenever it inserts stuff into the page DOM. This mostly means using secure facilities of your chosen framework, most modern frameworks are quite good at this by default, but you need to be aware what and how will actually be encoded an dinserted to prevent XSS. This is not at all straightforward in a complex SPA. Probably the most complex case is when you want to deliberately receive html from the client (say you have a html editor widget), save it to a server, and display it in the SPA again, possibly with a preview feature while editing, but this is a separate (large) topic, just something to be careful with.

One exception to the "not enconding stuff in the database" rule might be large, complex legacy applications. Sometimes you cannot guarantee that all (legacy) frontends to your data will apply proper encoding, so you might decide to encode data before writing it to the database. The problem with this is that then you cannot even write new code properly, because if you apply encoding again, data will be double encoded, which is also wrong.

🌐
Microsoft Learn
learn.microsoft.com › en-us › aspnet › core › security › cross-site-scripting
Prevent Cross-Site Scripting (XSS) in ASP.NET Core | Microsoft Learn
Tag helpers will also encode input you use in tag parameters. ... This view outputs the contents of the untrustedInput variable. This variable includes some characters which are used in XSS attacks, namely <, " and >. Examining the source shows the rendered output encoded as: