HttpUtility.HtmlEncode转义过多?
在我们的MVC3 ASP.net项目中,HttpUtility.HtmlEncode方法似乎在逃避太多字符。 我们的网页是以UTF-8页面的形式提供的,但是这种方法仍然可以避免使用像ü或Yen字符这样的字符,尽管tese字符是UTF-8的一部分。
所以,当我的asp.net MVC视图包含下面的一段代码:
    @("<strong>ümlaut</strong>")
然后,我希望编码器能够转义html标签,但不是ümlaut
    <strong>ümlaut</strong>
但相反,它给了我以下一段HTML:
    <strong>ümlaut</strong>
为了完整起见,我还提到web.config中的responseEncoding明确设置为utf-8,所以我希望HtmlEncode方法能够遵守这个设置。
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
是的,我面对与我的网页相同的问题。 如果我们看到htmlEncode的代码,则有一点可以翻译这组字符。 这是这种角色也翻译的代码。
if ((ch >= 'x00a0') && (ch < 'A'))
{
    output.Write("&#");
    output.Write(ch.ToString(NumberFormatInfo.InvariantInfo));
    output.Write(';');
}
else
{
    output.Write(ch);
}
这是HtmlEncode的代码
public static unsafe void HtmlEncode(string value, TextWriter output)
{
    if (value != null)
    {
        if (output == null)
        {
            throw new ArgumentNullException("output");
        }
        int num = IndexOfHtmlEncodingChars(value, 0);
        if (num == -1)
        {
            output.Write(value);
        }
        else
        {
            int num2 = value.Length - num;
            fixed (char* str = ((char*) value))
            {
                char* chPtr = str;
                char* chPtr2 = chPtr;
                while (num-- > 0)
                {
                    output.Write(chPtr2[0]);
                    chPtr2++;
                }
                while (num2-- > 0)
                {
                    char ch = chPtr2[0];
                    if (ch <= '>')
                    {
                        switch (ch)
                        {
                            case '&':
                            {
                                output.Write("&");
                                chPtr2++;
                                continue;
                            }
                            case ''':
                            {
                                output.Write("'");
                                chPtr2++;
                                continue;
                            }
                            case '"':
                            {
                                output.Write(""");
                                chPtr2++;
                                continue;
                            }
                            case '<':
                            {
                                output.Write("<");
                                chPtr2++;
                                continue;
                            }
                            case '>':
                            {
                                output.Write(">");
                                chPtr2++;
                                continue;
                            }
                        }
                        output.Write(ch);
                        chPtr2++;
                        continue;
                    }
                    // !here is the point!
                    if ((ch >= 'x00a0') && (ch < 'Ā'))
                    {
                        output.Write("&#");
                        output.Write(ch.ToString(NumberFormatInfo.InvariantInfo));
                        output.Write(';');
                    }
                    else
                    {
                        output.Write(ch);
                    }
                    chPtr2++;
                }
            }
        }
    }
}
一个可能的解决方案是制作自定义的HtmlEncode,或者使用来自MS的Anti-Cross Site脚本。
http://msdn.microsoft.com/en-us/security/aa973814
正如Aristos建议我们可以使用Microsoft的AntiXSS库。 它包含一个UnicodeCharacterEncoder,其行为与您所期望的相同。
但因为我们
我们选择实施我们自己的非常基本的HTML编码器。 你可以找到下面的代码。 如果您发现任何问题,请随时调整/评论/改进。
public static class HtmlEncoder
{
    private static IDictionary<char, string> toEscape = new Dictionary<char, string>()
                                                            {
                                                                { '<', "lt" },
                                                                { '>', "gt" },
                                                                { '"', "quot" },
                                                                { '&', "amp" },
                                                                { ''', "#39" },
                                                            };
    /// <summary>
    /// HTML-Encodes the provided value
    /// </summary>
    /// <param name="value">object to encode</param>
    /// <returns>An HTML-encoded string representing the provided value.</returns>
    public static string Encode(object value)
    {
        if (value == null)
            return string.Empty;
        // If value is bare HTML, we expect it to be encoded already
        if (value is IHtmlString)
            return value.ToString();
        string toEncode = value.ToString();
        // Init capacity to length of string to encode
        var builder = new StringBuilder(toEncode.Length);
        foreach (char c in toEncode)
        {
            string result;
            bool success = toEscape.TryGetValue(c, out result);
            string character = success
                                ? "&" + result + ";"
                                : c.ToString();
            builder.Append(character);
        }
        return builder.ToString();
    }
}
基于Thomas的回答,对空间,制表符和新行处理进行了一些改进,因为它们可能会破坏html的结构:
public static string HtmlEncode(string value,bool removeNewLineAndTabs)
    {
        if (value == null)
            return string.Empty;
        string toEncode = value.ToString();
        // Init capacity to length of string to encode
        var builder = new StringBuilder(toEncode.Length);
        foreach (char c in toEncode)
        {
            string result;
            bool success = toEscape.TryGetValue(c, out result);
            string character = success ? result : c.ToString();
            builder.Append(character);
        }
        string retVal = builder.ToString();
        if (removeNewLineAndTabs)
        {
            retVal = retVal.Replace("rn", " ");
            retVal = retVal.Replace("r", " ");
            retVal = retVal.Replace("n", " ");
            retVal = retVal.Replace("t", " ");
        }
        return retVal;
    }
上一篇: HttpUtility.HtmlEncode escaping too much?
下一篇: GET and $
