ASP.NET Web控件中的Html编码

cdu*_*dub 2 c# asp.net string html-encode

我有一个名为TopicTree.ascx.cs的文件,我试图输出编码的字符串,如下所示:

            string subject = reader.IsDBNull(0) ? string.Empty : reader.GetString(0);
            string topic = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);

            subject = subject.Trim();
            topic = topic.Trim();

            string en_subject = Server.HtmlEncode(subject);
            string en_topic = Server.HtmlEncode(topic);

            string output = string.Format("<li><a href=\"searchresults.aspx?type=topics&subject={1}&topic={2}\" style=\"cursor: pointer;\">{0}</a></li>", topic, en_subject, en_topic);
Run Code Online (Sandbox Code Playgroud)

但是当我实际看到屏幕上的输出时,它没有被编码.怎么了?

nek*_*kno 5

对于链接URL,您需要Server.UrlEncode()而不是Server.HtmlEncode().

但是对于链接显示,您也想要Server.HtmlEncode(topic)该主题.