What is the best way to fix “Improper Restriction of xml external entity reference”?

妖精的绣舞 提交于 2021-02-08 06:18:09

问题


We recently run VeraCode that points out on the following method:

    public XmlElement RunProcedureXmlElement(string Procedure, List<SqlParameter> Parameters)
    {
        DataSet ds = RunProcedureDataSet(Procedure, Parameters);
        XmlDocument xmlDoc = new XmlDocument();
        StringBuilder strXML = new StringBuilder();

        foreach (DataTable dt in ds.Tables)
        {
            foreach (DataRow dr in dt.Rows)
            {
                strXML.Append(dr[0]); // Do I still need .ToString()???
            }
        }
        if (strXML.Length == 0) strXML.Append("<root total=\"0\"></root>");

        try
        {
            xmlDoc.LoadXml(strXML.ToString());
        }
        catch (XmlException e)
        {

        }

        return xmlDoc.DocumentElement;
    }

What would be a good solution to fix that method so VeraCode stops complaining?

Thank's


回答1:


I also had the same issue with Veracode, and the following resolved it.
After declaring XmlReader:

XmlDocument xmlDoc = new XmlDocument();

Add line:

xmlDoc.XmlResolver = null;



回答2:


After doing some research, this piece of code should fix it:

        using (System.IO.MemoryStream stream = new System.IO.MemoryStream (Encoding.Default.GetBytes(strXML.ToString())))
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.DtdProcessing = DtdProcessing.Prohibit;
            using (XmlReader reader = XmlReader.Create(stream, settings))
            {
                try
                {
                    xmlDoc.Load(reader);
                }
                catch(XmlException e)
                {

                }
            }
        }



回答3:


I used following example to solve this issues

  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.XmlResolver = null;
  xmlDoc.LoadXml(strXML.ToString());



回答4:


From VS2017 IDE advice, you could correct it by this :

    XmlDocument xmlDoc = new XmlDocument { XmlResolver = null };


来源:https://stackoverflow.com/questions/21938048/what-is-the-best-way-to-fix-improper-restriction-of-xml-external-entity-referen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!