C# 在 .NET 中有等效于PHP中的 htmlspecialcharacters的函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHPs htmlspecialcharacters equivalent in .NET?
提问by Adam
PHP has a great function called htmlspecialcharacters()where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's almosta one stop shop for sanitizing input. Very nice right?
PHP 有一个很棒的函数,叫做htmlspecialcharacters(),你可以在其中传递一个字符串,它会用安全的等价物替换所有 HTML 的特殊字符,它几乎是清理输入的一站式商店。很不错吧?
Well is there an equivalent in any of the .NET libraries?
那么在任何 .NET 库中是否有等价物?
If not, can anyone link to any code samples or libraries that do this well?
如果没有,任何人都可以链接到任何做得很好的代码示例或库吗?
采纳答案by Nick Berardi
Try this.
尝试这个。
var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);
回答by Forgotten Semicolon
回答by Jason Shoulders
Don't know if there's an exact replacement, but there is a method HtmlUtility.HtmlEncode
that replaces special characters with their HTML equivalents. A close cousin is HtmlUtility.UrlEncode
for rendering URL's. You could also use validator controls like RegularExpressionValidator
, RangeValidator
, and System.Text.RegularExpression.Regex
to make sure you're getting what you want.
不知道是否有确切的替换,但有一种方法HtmlUtility.HtmlEncode
可以用它们的 HTML 等效项替换特殊字符。一个近亲HtmlUtility.UrlEncode
用于呈现 URL。您还可以使用RegularExpressionValidator
、RangeValidator
、 等验证器控件,System.Text.RegularExpression.Regex
以确保获得所需的内容。
回答by michalstanko
Actually, you might want to try this method:
实际上,您可能想尝试以下方法:
HttpUtility.HtmlAttributeEncode()
Why? Citing the HtmlAttributeEncode page at MSDN docs:
为什么?引用MSDN 文档中的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.
HtmlAttributeEncode 方法仅将引号 (")、与号 (&) 和左尖括号 (<) 转换为等效的字符实体。它比 HtmlEncode 方法快得多。
回答by Memet Olsen
In an addition to the given answers: When using Razor view engine(which is the default view engine in ASP.NET), using the '@' character to display values will automatically encode the displayed value. This means that you don't have to use encoding.
除了给定的答案:使用Razor 视图引擎(这是 ASP.NET 中的默认视图引擎)时,使用“@”字符显示值将自动对显示值进行编码。这意味着您不必使用编码。
On the other hand, when you don'twant the text being encoded, you have to specify that explicitly (by using @Html.Raw). Which is, in my opinion, a good thing from a security point of view.
在另一方面,当你不希望被编码的文本,您必须指定明确(通过使用@ Html.Raw)。在我看来,从安全的角度来看,这是一件好事。