How to configure the XML parser to disable external entity resolution in c#

后端 未结 3 1924
粉色の甜心
粉色の甜心 2020-12-30 04:00
var xDoc = XDocument.Load(fileName);

I am using above code in a function to load an XML file. Functionality wise its working fine but it is showing

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 04:33

    Implement a custom XmlResolver and use it for reading the XML. By default, the XmlUrlResolver is used, which automatically downloads the resolved references.

    public class CustomResolver : XmlUrlResolver
    {
        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
        {
            // base calls XmlUrlResolver.DownloadManager.GetStream(...) here
        }
    }
    

    And use it like this:

    var settings = new XmlReaderSettings { XmlResolver = new CustomResolver() };
    var reader = XmlReader.Create(fileName, settings);
    var xDoc = XDocument.Load(reader);
    

提交回复
热议问题