program tip

MS Ajax에서 사용하기 위해 .NET 문자열을 JavaScript 문자열로 인코딩하는 표준 방법이 있습니까?

radiobox 2020. 10. 23. 07:45
반응형

MS Ajax에서 사용하기 위해 .NET 문자열을 JavaScript 문자열로 인코딩하는 표준 방법이 있습니까?


RegisterStartUpScript.NET 3.5에서 MS ScriptManager 방법을 사용하여 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();
    }
}

아래에 언급 된대로-원본 출처 : 여기


봤어 HttpUtility.JavaScriptStringEncode?


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


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

참고URL : https://stackoverflow.com/questions/2920752/is-there-a-standard-way-to-encode-a-net-string-into-javascript-string-for-use-i

반응형