简体   繁体   English

C#ASP.NET文本框双重HTMLEncode和防止XSS

[英]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. 我想防止XSS,所以在使用HTMLUtility.HtmlEncode对所有数据进行编码之前,将其显示在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 摘自Microsoft的“ 如何:防止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. 如果您的页面需要接受一定范围的HTML元素,例如通过某种富文本输入字段,则必须禁用该页面的ASP.NET请求验证。 If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. 如果有多个页面可以执行此操作,请创建一个过滤器,该过滤器仅允许您要接受的HTML元素。 A common practice is to restrict formatting to safe HTML elements such as bold () and italic (). 通常的做法是将格式限制为安全的HTML元素,例如粗体()和斜体()。

To safely allow restricted HTML input 为了安全地允许受限制的HTML输入

 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. 看起来不太优雅,但这直接来自MSDN。

You don't have to explicitly encode the ASPNET TextBox. 您不必显式编码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; 这就是为什么它显示&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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