XmlReaderSettings.MaxCharactersInDocument 属性

定义

获取或设置一个值,该值指明 XML 文档中所允许的最大字符数。Gets or sets a value indicating the maximum allowable number of characters in an XML document. 零 (0) 值表示对 XML 文档的大小没有限制。A zero (0) value means no limits on the size of the XML document. 非零值指定最大大小(以字符数计)。A non-zero value specifies the maximum size, in characters.

public:
 property long MaxCharactersInDocument { long get(); void set(long value); };
public long MaxCharactersInDocument { get; set; }
member this.MaxCharactersInDocument : int64 with get, set
Public Property MaxCharactersInDocument As Long

属性值

Int64

XML 文档中所允许的最大字符数。The maximum allowable number of characters in an XML document. 默认值为 0。The default is 0.

示例

下面的代码设置此属性,然后尝试分析大于限制的文档。The following code sets this property, and then attempts to parse a document larger than the limit. 在实际方案中,您需要将此限制设置为一个足够大的值,以处理有效文档,而不是足够小,以限制恶意文档的威胁。In a real world scenario, you would set this limit to a value large enough to handle valid documents, yet small enough to limit the threat from malicious documents.

string markup = "<Root>Content</Root>";  

XmlReaderSettings settings = new XmlReaderSettings();  
settings.MaxCharactersInDocument = 10;  

try  
{  
    XmlReader reader = XmlReader.Create(new StringReader(markup), settings);  
    while (reader.Read()) { }  
}  
catch (XmlException ex)  
{  
    Console.WriteLine(ex.Message);  
}  
Dim markup As String = "<Root>Content</Root>"  

Dim settings As XmlReaderSettings = New XmlReaderSettings()  
settings.MaxCharactersInDocument = 10  

Try  
    Dim reader As XmlReader = XmlReader.Create(New StringReader(markup), settings)  
    While (reader.Read())  
    End While  
Catch ex As XmlException  
    Console.WriteLine(ex.Message)  
End Try  

此代码生成以下输出:This code produces the following output:

There is an error in XML document (MaxCharactersInDocument, ).  

注解

零 (0) 值意味着对分析文档中的字符数没有限制。A zero (0) value means no limits on the number of characters in the parsed document. 非零值指定可分析的最大字符数。A non-zero value specifies the maximum number of characters that can be parsed.

文档的最大字符数包括扩展的实体产生的字符数。The maximum character count for the document includes the count of characters that result from expanded entities.

如果读取器尝试读取大小超过此属性的文档, XmlException 将引发。If the reader attempts to read a document with a size that exceeds this property, an XmlException will be thrown.

此属性允许你缓解拒绝服务攻击,攻击者可以在其中提交非常大的 XML 文档。This property allows you to mitigate denial of service attacks where the attacker submits extremely large XML documents. 通过限制文档的大小,可以检测到攻击并可靠地进行恢复。By limiting the size of a document, you can detect the attack and recover reliably.

适用于