SecurityElement.IsValidText在"&"上返回true ...为什么?

9

我有一个文本框,最终保存在一个xml节点中。我使用SecurityElement.Escape(string2Escape)来转义无效字符,然后保存xml。

问题:我尝试使用IsValidText测试是否需要运行转义方法,但它将'''和'&'视为有效,但当你保存xml时,系统会报错,因为它们实际上是无效的。似乎只有'<'或'>'返回false。

简单的解决方案是删除检查,但我的问题是为什么会出现这种情况?

以下是我的失败代码:

private string EscapeXML(string nodeText)
{
    if (!SecurityElement.IsValidText(nodeText))
    {
        return SecurityElement.Escape(nodeText);
    }
    return nodeText;
}
2个回答

5

我从Reflector中得到了这些信息。 enter image description here enter image description here

这可以解释为什么它的行为是这样的。我没有看到SecurityElement中有任何方法可以做到您要寻找的功能,但是您可以自己实现一个,可能作为扩展方法。


2

SecurityElement构造函数似乎已经在自己进行某些转义(包括"&"字符),因此IsValidText似乎只检查构造函数没有处理的字符。

因此,除非您使用SecurityElement来构建整个xml,否则使用SecurityElement的IsValidText / Escape组合看起来不安全。

我将用一个例子更好地解释:

using System;
using System.Diagnostics;
using System.Security;

class MainClass
{
    public static void Main (string[] args)
    {
        // the SecurityElement constructor escapes the & all by itself 
        var xmlRoot =
            new SecurityElement("test","test &");

        // the & is escaped without SecurityElement.Escape 
        Console.WriteLine (xmlRoot.ToString());

        // this would throw an exception (the SecurityElement constructor
        // apparently can't escape < or >'s
        // var xmlRoot2 =
        //    new SecurityElement("test",@"test & > """);

        // so this text needs to be escaped before construction 
        var xmlRoot3 =
            new SecurityElement("test",EscapeXML(@"test & > """));
        Console.WriteLine (xmlRoot3.ToString());

    }

    private static string EscapeXML(string nodeText)
    {
        return (SecurityElement.IsValidText(nodeText))?
            nodeText :
            SecurityElement.Escape(nodeText);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接