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

lga*_*dos 9 c# xml asp.net

我有一个TextBox,最终保存在xml节点中.我在保存xml之前使用SecurityElement.Escape(string2Escape)来转义无效字符.

问题:我尝试使用IsValidText测试我是否需要运行escape方法,但它返回'''和'&'作为有效,但是当你保存xml系统barfs时,因为它们实际上是无效的.它似乎只在'<'或'>'上返回false.

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

以下是我失败的代码:

private string EscapeXML(string nodeText)
{
    if (!SecurityElement.IsValidText(nodeText))
    {
        return SecurityElement.Escape(nodeText);
    }
    return nodeText;
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*a R 5

这是我从Reflector得到的. 在此输入图像描述 在此输入图像描述

这可以解释为什么它的行为方式.我没有在SecurityElement中看到任何方法来执行您正在寻找的内容,但它很简单,您可以自己实现,也许作为扩展方法.


Pao*_*lla 2

SecurityElement 构造函数显然已经自行进行了一些转义(包括“&”字符),因此 IsValidText 似乎只检查构造函数尚未处理的字符。因此,使用 SecurityElement 的 IsValidText/Escape 组合看起来并不安全,除非您使用 SecurityElement 构建整个 xml。

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)