HttpUtility.HtmlEncode doesn't encode everything

后端 未结 7 960
南方客
南方客 2020-12-16 13:45

I am interacting with a web server using a desktop client program in C# and .Net 3.5. I am using Fiddler to see what traffic the web browser sends, and emulate that. Sadly t

7条回答
  •  不知归路
    2020-12-16 14:04

    Rich Strahl just posted a blog post, Html and Uri String Encoding without System.Web, where he has some custom code that encodes the upper range of characters, too.

    /// 
    /// HTML-encodes a string and returns the encoded string.
    /// 
    /// The text string to encode. 
    /// The HTML-encoded text.
    public static string HtmlEncode(string text)
    {
        if (text == null)
            return null;
    
        StringBuilder sb = new StringBuilder(text.Length);
    
        int len = text.Length;
        for (int i = 0; i < len; i++)
        {
            switch (text[i])
            {
    
                case '<':
                    sb.Append("<");
                    break;
                case '>':
                    sb.Append(">");
                    break;
                case '"':
                    sb.Append(""");
                    break;
                case '&':
                    sb.Append("&");
                    break;
                default:
                    if (text[i] > 159)
                    {
                        // decimal numeric entity
                        sb.Append("&#");
                        sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture));
                        sb.Append(";");
                    }
                    else
                        sb.Append(text[i]);
                    break;
            }
        }
        return sb.ToString();
    }
    

提交回复
热议问题