【问题标题】:How to prevent escaping of text in C# for ASP.NET?如何防止在 C# for ASP.NET 中转义文本?
【发布时间】:2012-09-30 00:38:51
【问题描述】:

我有以下代码为我为 ASP.NET 编写的 Web 应用程序的浏览器提示添加了一个换行符:

RectangleHotSpot rhs = new RectangleHotSpot();
rhs.HotSpotMode = HotSpotMode.Navigate;
rhs.AlternateText = "Line one
Line Two"; //New-line to conform with FF
rhs.NavigateUrl = "my URL";

ImageMap.HotSpots.Add(rhs);

但由于某种原因,'rhs.AlternateText' 被转义为:

“第一行
第二行”

当我在网络浏览器中查看源代码时。 (我不得不在上面添加空格,因为这个网站也逃脱了它:)

有什么办法可以防止吗?

【问题讨论】:

    标签: c# asp.net escaping


    【解决方案1】:

    试试这样的:

        public class RectangleHotSpot : System.Web.UI.WebControls.HotSpot
    {
        private string _strAlt;
        public override string AlternateText
        {
            get
            {
                return _strAlt;
            }
            set
            {
                this._strAlt = value;
            }
        }
    
        public override string GetCoordinates()
        {
            return String.Empty; // You'll need to fill this in.
        }
    
        protected override string MarkupName
        {
            get { return String.Empty; } // This too.
        }
    }
    

    GetCoordinates 和 MarkupName 作为抽象成员的一部分是必需的,但我不熟悉 Rectangle Hot Spot 类,所以我不确定你会在那里替换什么。

    【讨论】:

    • 这也不起作用。该值由父控件编码。在这一点上,我只会从头开始制作您需要的控件。对不起,我不能更有帮助! :(
    • 谢谢。这似乎是 ASP.NET 的内置函数来编码这些字符串?
    • 是的。使用 HtmlTextWriter 时,它似乎在调用 .WriteEncodedText(string)。出于纯粹的挫败感,我什至尝试覆盖 ImageMap 控件的渲染功能并手动删除 Attributes["alt"] 并使用示例中字符串的硬编码副本重新添加 Attributes["alt"],但没有修改正在对该输入值进行处理,直到根据我的判断将其写入输出流。到 2.0 发布时,我真的不再依赖 WebControls。通过创建自定义控件可以省去很多麻烦,尤其是在您开始构建库时。
    • 感谢您的尝试。确实令人沮丧。我可能最终只是通过纯 HTML “组合”它。我不太擅长编写自己的控件...
    • 真的很简单。考虑以下内容并从那里开始: public class TestControl : System.Web.UI.Control { protected override Render(System.Web.UI.HtmlTextWriter writer) { writer.WriteLine("Hi world."); } }
    【解决方案2】:

    这是因为当它出现在属性引号中时,这是使用它的正确 (W3C) 方式。我不熟悉您使用的确切控件,但请参阅下面的示例:

    <img src="img/wrong.jpg" alt="This is the wrong way &#013; because the ampersand is not encoded properly for attributes" />
    
    <img src="img/correct.jpg" alt="This is the right way &amp;#013 because the ampersand IS escaped and the browser will read &amp; as just an ampersand plus the code, which is what you want." />
    

    【讨论】:

    • 如果他输出的行在HTML的属性引号中,那么这样是正确的。您必须双重转义:一次用于 HTML,另一次用于属性。
    • 我得到的是你不想改变它。它为你做的方式是正确的。
    • 如果输出未包含在属性引号内,则尝试使用 HtmlString 对象,如下所示:rhs.AlternateText = new System.Web.HtmlString("Line one Line Two");
    • 其实,只要把输出的HTML输出照原样张贴出来,我就能告诉你应该是什么。
    • 删除了所有对这个问题不重要的标签/属性,生成的 HTML 应该是: Line one
Line Two
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多