是否有一种标准方法可以将 .NET 字符串编码为 JavaScript 字符串以便在 MS Ajax 中使用?

发布于 2024-09-03 08:11:30 字数 2382 浏览 4 评论 0原文

我尝试使用 .NET 3.5 中 MS ScriptManager 的 RegisterStartUpScript 方法将 SQL Server 异常的输出传递给客户端。这对于某些错误来说效果很好,但是当异常包含单引号时,警报会失败。

但我不想只转义单引号。是否有一个标准函数可以调用来转义 JavaScript 中使用的任何特殊字符?

string scriptstring = "alert('" + ex.Message + "');";         
ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", scriptstring , true);

编辑

谢谢@tpeczek,代码几乎对我有用:),但是经过一些小小的修改(单引号的转义),它就很不错了。

我已将修改后的版本放在这里...

public class JSEncode
{
    /// <summary>
    /// Encodes a string to be represented as a string literal. The format
    /// is essentially a JSON string.
    /// 
    /// The string returned includes outer quotes 
    /// Example Output: "Hello \"Rick\"!\r\nRock on"
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string EncodeJsString(string s)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("\"");
        foreach (char c in s)
        {
            switch (c)
            {
                case '\'':
                    sb.Append("\\\'");
                    break;
                case '\"':
                    sb.Append("\\\"");
                    break;
                case '\\':
                    sb.Append("\\\\");
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                default:
                    int i = (int)c;
                    if (i < 32 || i > 127)
                    {
                        sb.AppendFormat("\\u{0:X04}", i);
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;
            }
        }
        sb.Append("\"");

        return sb.ToString();
    }
}

如下所述 - 原始来源:此处

I'm trying to pass the output of a SQL Server exception to the client using the RegisterStartUpScript method of the MS ScriptManager in .NET 3.5. This works fine for some errors but when the exception contains single quotes the alert fails.

I dont want to only escape single quotes though. Is there a standard function I can call to escape any special chars for use in JavaScript?

string scriptstring = "alert('" + ex.Message + "');";         
ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", scriptstring , true);

EDIT:

Thanks @tpeczek, the code almost worked for me :) but with a slight amendment (the escaping of single quotes) it works a treat.

I've included my amended version here...

public class JSEncode
{
    /// <summary>
    /// Encodes a string to be represented as a string literal. The format
    /// is essentially a JSON string.
    /// 
    /// The string returned includes outer quotes 
    /// Example Output: "Hello \"Rick\"!\r\nRock on"
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string EncodeJsString(string s)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("\"");
        foreach (char c in s)
        {
            switch (c)
            {
                case '\'':
                    sb.Append("\\\'");
                    break;
                case '\"':
                    sb.Append("\\\"");
                    break;
                case '\\':
                    sb.Append("\\\\");
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                default:
                    int i = (int)c;
                    if (i < 32 || i > 127)
                    {
                        sb.AppendFormat("\\u{0:X04}", i);
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;
            }
        }
        sb.Append("\"");

        return sb.ToString();
    }
}

As mentioned below - original source: here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱的十字路口 2024-09-10 08:11:30

使用此函数的一个问题是,它不会对封装 HTML 时通常带外的字符进行编码...因此,如果您尝试在内部包含带有 " 的字符串,则会遇到麻烦属性值,或者如果脚本元素内有一个带有 序列的字符串,则可能会导致脚本注入和

XSS

            case '<':
                sb.Append("\\x3C");
                break;
            case '"':
                sb.Append("\\x22");
                break;
            case '&':
                sb.Append("\\x26");
                break;

。使用标准 JSON 编码器比编写自己的 JS 字符串文字编码器更好,这将允许您将任何简单的数据类型传递给 JS,而不仅仅是字符串。

在 .NET 3.5 中,您将得到 JavaScriptSerializer,但请注意,虽然这确实编码 <\u003C (因此输出适合在

(与许多 JSON 编码器一样,它也无法对 U+2028 行分隔符和 U+2029 段落分隔符字符进行编码。由于转义了所有非 ASCII 字符,上述代码确实如此。这会导致“未终止的字符串文字”错误这些字符包含在 JS 字符串文字中,因为 JavaScript 毫无帮助地将它们视为 ASCII 换行符。)

A probem with this function is that it doesn't encode characters that are typically out-of-band in encapsulating HTML... so you'd have trouble if you tried to include a string with " inside an attribute value, or if you had a string with the sequence </script> inside a script element. That could lead to script-injection and XSS.

You could add:

            case '<':
                sb.Append("\\x3C");
                break;
            case '"':
                sb.Append("\\x22");
                break;
            case '&':
                sb.Append("\\x26");
                break;

In general it would probably be better to use a standard JSON encoder than brew your own JS string literal encoder. This will allow you to pass any simple datatype to JS rather than just strings.

In .NET 3.5 you get JavaScriptSerializer, however note that whilst this does encode < to \u003C (so the output will be suitable for use in a <script> element), it doesn't encode & or ", so HTML-escaping would be needed to include such content in an attribute value and a CDATA wrapper would be needed for XHTML script elements.

(In common with many JSON encoders, it also fails to encode the U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR characters. The above code does, due to escaping all non-ASCII characters. This causes ‘unterminated string literal’ errors when these characters are included in a JS string literal, because JavaScript unhelpfully treats them the same as an ASCII newline.)

自此以后,行同陌路 2024-09-10 08:11:30

这是一个旧线程,但您可能有兴趣了解 Microsoft AntiXSS 库,该库具有适用于 .Net 2 及以上版本的 Javascript 编码方法。

http://msdn.microsoft.com/en-gb/security/aa973814.aspx

This is an old thread, but you may be interested to know about the Microsoft AntiXSS library which has a Javascript encode method which works for .Net 2 onwards.

http://msdn.microsoft.com/en-gb/security/aa973814.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文