从 ASP.NET 转义 JavaScript 特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27530729/
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
Escaping JavaScript special characters from ASP.NET
提问by Joe Schmoe
I have following C# code in my ASP.NET application:
我的 ASP.NET 应用程序中有以下 C# 代码:
string script = @"alert('Message head:\n\n" + CompoundErrStr + " message tail.');";
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", script, true);
CompoundErrStr is an error message generated by SQL Server (exception text bubbled up from the stored procedure). If it contains any table column names they are enclosed in single quotes and JavaScript breaks during execution because single quotes are considered a string terminator.
CompoundErrStr 是 SQL Server 生成的错误消息(从存储过程冒泡的异常文本)。如果它包含任何表列名称,则它们会用单引号括起来,并且 JavaScript 在执行期间会中断,因为单引号被视为字符串终止符。
As a fix for single quotes I changed my code to this:
作为单引号的修复,我将代码更改为:
CompoundErrStr = CompoundErrStr.Replace("'", @"\'");
string script = @"alert('Message head:\n\n" + CompoundErrStr + " message tail.');";
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", script, true);
and it now works fine.
现在工作正常。
However, are there any other special characters that need to be escaped like this? Is there a .Net function that can be used for this purpose? Something similar to HttpServerUtility.HtmlEncode but for JavaScript.
但是,是否还有其他特殊字符需要像这样转义?是否有可用于此目的的 .Net 函数?类似于 HttpServerUtility.HtmlEncode 但用于 JavaScript。
EDITI use .Net 3.5
编辑我使用 .Net 3.5
回答by Adriano Repetti
Note: for this task you can't (and you shouldn't) use HTML encoders (like HttpServerUtility.HtmlEncode()
) because rules for HTML and for JavaScript strings are pretty different. One example: string "Check your Windows folder c:\windows"
will be encoded as "Check your Windows folder c:'windows"
and it's obviously wrong. Moreover it follows HTML encoding rules then it won't perform any escaping for \, "and '. Simply it's for something else.
注意:对于此任务,您不能(也不应该)使用 HTML 编码器(例如HttpServerUtility.HtmlEncode()
),因为 HTML 和 JavaScript 字符串的规则非常不同。一个例子:字符串"Check your Windows folder c:\windows"
将被编码为"Check your Windows folder c:'windows"
,这显然是错误的。此外,它遵循 HTML 编码规则,因此不会对\,"和进行任何转义'。只是为了别的东西。
If you're targeting .NET 4 (or higher) you do not need to do it manually and you can directly use newly added HttpUtility.JavaScriptStringEncode()method.
如果您的目标是 .NET 4(或更高版本),则不需要手动执行此操作,您可以直接使用新添加的HttpUtility.JavaScriptStringEncode()方法。
If you're targeting ASP.NET Core then you should use System.Text.Encodings.Web.JavaScriptEncoder
instead.
如果您的目标是 ASP.NET Core,那么您应该System.Text.Encodings.Web.JavaScriptEncoder
改用。
What do you have to encode? Some characters must be escaped (\, "and ') because they have specialmeaning for JavaScript parser while others may interfere with HTML parsing so should escaped too (if JS is inside an HTML page). You have two options for escaping: JavaScript escape character \or \uxxxx
Unicode code points (note that \uxxxx
may be used for them all but it won't work for characters that interferes with HTML parser).
你必须编码什么?某些字符(\,"和')必须转义,因为它们对 JavaScript 解析器具有特殊含义,而其他字符可能会干扰 HTML 解析,因此也应该转义(如果 JS 在 HTML 页面内)。您有两种转义选项:JavaScript 转义字符\或\uxxxx
Unicode 代码点(请注意,它们\uxxxx
可能全部使用,但不适用于干扰 HTML 解析器的字符)。
You may do it manually (with search and replace) like this:
您可以像这样手动执行(使用搜索和替换):
string JavaScriptEscape(string text)
{
return text
.Replace("\", @"\u005c") // Because it's JS string escape character
.Replace("\"", @"\u0022") // Because it may be string delimiter
.Replace("'", @"\u0027") // Because it may be string delimiter
.Replace("&", @"\u0026") // Because it may interfere with HTML parsing
.Replace("<", @"\u003c") // Because it may interfere with HTML parsing
.Replace(">", @"\u003e"); // Because it may interfere with HTML parsing
}
Of course \should not be escaped if you're using it as escape character! This blindreplacement is useful for unknowntext (like input from users or text messages that may be translated). Note that if string is enclosed with double quotes then single quotes don't need to be escaped and vice-versa). Be careful to keep verbatim strings on C# code or Unicode replacement will be performed in C# and your client will receive unescaped strings. A note about interfere with HTML parsing: nowadays you seldom need to create a <script>
node and to inject it in DOM but it was a pretty common technique and web is full of code like + "</s" + "cript>"
to workaround this.
当然,\如果您将其用作转义字符,则不应转义!这种盲目替换对未知文本很有用(例如来自用户的输入或可能被翻译的文本消息)。请注意,如果字符串用双引号括起来,则单引号不需要转义,反之亦然)。小心在 C# 代码中保留逐字字符串,否则 Unicode 替换将在 C# 中执行,您的客户端将收到未转义的字符串。关于干扰 HTML 解析的注意事项:现在您很少需要创建<script>
节点并将其注入 DOM 中,但这是一种非常常见的技术,网络上充满了类似+ "</s" + "cript>"
解决此问题的代码。
Note: I said blindescaping because if your string contains an escape sequence (like \uxxxx
or \t
) then it should not be escaped again. For this you have to do some tricks around this code.
注意:我说盲目转义是因为如果您的字符串包含转义序列(如\uxxxx
或\t
),则不应再次对其进行转义。为此,您必须围绕此代码做一些技巧。
If your text comes from user input and it may be multiline then you should also be ready for that or you'll have broken JavaScript code like this:
如果您的文本来自用户输入并且可能是多行的,那么您也应该为此做好准备,否则您将破坏 JavaScript 代码,如下所示:
alert("This is a multiline
comment");
Simply add .Replace("\n", "\\n").Replace("\r", "")
to previous JavaScriptEscape()
function.
只需添加.Replace("\n", "\\n").Replace("\r", "")
到以前的JavaScriptEscape()
功能。
For completeness: there is also another method, if you encode your string Uri.EscapeDataString()
then you can decode it in JavaScript with decodeURIComponent()
but this is more a dirty trick than a solution.
为了完整性:还有另一种方法,如果您对字符串进行编码,Uri.EscapeDataString()
那么您可以使用 JavaScript 对其进行解码,decodeURIComponent()
但这与其说是解决方案,不如说是一个肮脏的技巧。
回答by Charles Burns
While the original question mentions .NET 3.5, it should be known to users of 4.0+ that you can use HttpUtility.JavaScriptStringEncode("string")
虽然最初的问题提到了 .NET 3.5,但 4.0+ 的用户应该知道您可以使用 HttpUtility.JavaScriptStringEncode("string")
A second bool parameter specifies whether to include quotation marks (true) or not (false) in the result.
第二个 bool 参数指定结果中是否包含引号 (true) 或不包含引号 (false)。
回答by BuddyZ
All too easy:
太简单了:
@Html.Raw(myString)