如何在ASP.NET MVC中使用ActionResult返回带有声明的Xml?

时间:2018-08-22 20:49:43

标签: c# xml asp.net-mvc

使用“操作结果”返回xml时,我无法附加xml声明。 我可以看到它在调试时被包括在内,直到它在下面的代码中返回xml的行,但未在网络上显示。

我目前正在做什么:

  1. 使用XML PATH从Sql Server中获取Xml。
  2. 使用XML Reader返回xml字符串:

    public XmlDocumentResult XmlData()
    {
        String s = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "\n" +  this.GetData();
        byte[] encodedString = Encoding.UTF8.GetBytes(s);
        MemoryStream ms = new MemoryStream(encodedString);
        ms.Flush();
        ms.Position = 0;
        XmlDocument doc = new XmlDocument();
        doc.Load(ms);           
        return new XmlDocumentResult { XmlDocument = doc };
    }
    
    public class XmlDocumentResult : ContentResult
     {
         public XmlDocument XmlDocument { get; set; }
    
         public override void ExecuteResult(ControllerContext context)
         {
             if (XmlDocument == null)
                 return;
    
             Content = XmlDocument.OuterXml;
             ContentType = "text/xml";
             base.ExecuteResult(context);
         }
     }
    

我尝试了以下Stackoverflow中的代码段:

XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);


XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);

1 个答案:

答案 0 :(得分:2)

也许尝试一下:

public IActionResult Index()
{
    // you need to convert your xml to string
    var xmlString = "xml content..";
    return this.Content(xmlString, "text/xml");
}

请参见https://docs.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd492713%28v%3dvs.100%29