简体   繁体   中英

C# ASP.NET textbox double HTMLEncode and Preventing XSS

I want to prevent XSS, so I'm using HTMLUtility.HtmlEncode to encode all data before showing it in ASPNET TextBox. But instead of showing proper characters for & , I see & amp; .

What should I do to fix it?

Thank you!

Taken from Microsoft's How To: Prevent Cross-Site Scripting in ASP.NET

Filter User Input

If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold () and italic ().

To safely allow restricted HTML input

 Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive. Encode the string input with the HtmlEncode method. **Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.** 

based on this, it would seem the best practice is to search and replace & amp; with &. Doesn't seem very elegant but this is straight from MSDN.

You don't have to explicitly encode the ASPNET TextBox. For text boxes out put is already encoded. If you encode it again, it will be double encoded. That is why it is showing & amp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM