从ASP.NET JavaScript的转义特殊字符 [英] Escaping JavaScript special characters from ASP.NET

查看:400
本文介绍了从ASP.NET JavaScript的转义特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的ASP.NET应用程序下面的C#code:

I have following C# code in my ASP.NET application:

string script = @"alert('Message head:\n\n" + CompoundErrStr + " message tail.');";
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", script, true);

CompoundErrStr是由SQL Server生成错误消息(异常文本从存储过程冒泡)。如果它包含任何表的列名它们用单引号和JavaScript,因为单引号被认为是一个字符串结束执行过程中中断。

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.

对于单引号修复我改变了我的code这样:

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);

和现在工作得很好。

不过,是否有需要进行转义像这样的任何其它特殊字符?是否有可用于该目的的净功能?类似的东西来HttpServerUtility.HtmlEn code,但对JavaScript。

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 3.5

EDIT I use .Net 3.5

推荐答案

注意:这个任务你不能(和你不应该)使用HTML EN codeRS(如 HttpServerUtility.HtmlEn code()),因为HTML和JavaScript的字符串规则是pretty不同。举个例子:字符串检查您的Windows文件夹C:\\ WINDOWS将连接codeD为检查您的Windows文件夹C:放大器; #39;窗口键,这显然是错误的。此外,它遵循HTML编码规则,那么就不会执行任何转义<大骨节病> \\ 和<大骨节病> 。只要它是别的东西。

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:&#39;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.

你有什么要带code ?有些字符必须进行转义(<大骨节病> \\ 和<大骨节病> ),因为他们的特殊的意思是JavaScript的解析器,而其他。可以用HTML解析所以要躲过太(如果JS是一个HTML页面内)干扰您有逃避两种选择:JavaScript的转义符<大骨节病> \\ 为\\ uXXXX 的Uni code code点(注意,为\\ uXXXX 可用于所有这些,但它不会与HTML解析器干扰字符工作)。

What do you have to encode? Some characters must be escaped (\, " and ') because they have special meaning 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).

您可以做手工(与搜索和替换)是这样的:

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
}

当然,<大骨节病> \\ 如果你使用它作为转义字符不应该逃脱!这的盲目的替代是有用的未知的文本(比如从用户或短信输入可翻译)。请注意,如果字符串括双引号则单引号不需要进行转义和反之亦然的)。要小心,保持对C#code或单向code更换逐字字符串将在C#中进行,你的客户会收到转义字符串。有关的与HTML解析干扰的说明的:现在你很少需要创建一个&LT;脚本&GT; 节点,并注入其在DOM,但它是一个pretty常见的技术和网络是充满code像 +&LT; / s的+CRIPT&gt;中。来解决此

Of course \ should not be escaped if you're using it as escape character! This blind replacement is useful for unknown text (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.

请注意:我说的盲目的转义,因为如果您的字符串包含转义序列(如为\\ uXXXX \\ t ),那么它不应该再次逃脱。为此,您需要做的解决这个code一些技巧。

Note: I said blind escaping 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.

如果您的文本来自用户的输入,它可能是多行,那么你也应该做好准备,否则你会打破的JavaScript code是这样的:

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:

alert("This is a multiline
comment");

只需添加 .Replace(\\ n,\\\\ N)。替换(\\ r,即)来previous JavaScriptEscape()功能。

Simply add .Replace("\n", "\\n").Replace("\r", "") to previous JavaScriptEscape() function.

如果你的目标.NET 4.0(或更高版本),你不需要手动做到这一点,你可以直接使用新增的 HttpUtility.JavaScriptStringEn code()方法

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.

有关完整性:也有另一种方法,如果你带code你的字符串 Uri.EscapeDataString(),那么你可以在JavaScript中去code将其与德codeURIComponent()但是这更多的是一个肮脏的伎俩不是一个解决方案。

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.

这篇关于从ASP.NET JavaScript的转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆