使用“操作结果”返回xml时,我无法附加xml声明。 我可以看到它在调试时被包括在内,直到它在下面的代码中返回xml的行,但未在网络上显示。
我目前正在做什么:
使用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);
答案 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